<?php

namespace app\api\controller;

use app\facade\Redis;
use app\models\{Marks, Signexcel, Admin, Zhaopai, Wenjian, Liaotian, Kaoke, Sucai, Annous, Annouslog, Dingorxuan, Leave, User as Users, Config, Business, Message as Messages, Reimburs, ReimbursLog, Biaoji, Uploadtk, Businessxq, Signlog, Sign, Userstatus};
use think\Facade\Config as Configs;
use EasyWeChat\Factory;
use think\Validate;
use think\Db;
use think\facade\Debug;
use think\facade\Log;
use FFMpeg\FFMpeg;

class Task extends Base
{

    public function upaddress()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
                'reAddress' => 'require',
                'address' => 'require',
                'lat' => 'require',
                'lon' => 'require',
            ], [
                'id.require' => 'ID不能为空',
                'reAddress.require' => '定位地址不能为空',
                'lat.require' => '坐标地址错误，请重新定位',
                'lon.require' => '坐标地址错误，请重新定位',
                'address.require' => '详细地址不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $order = (new Business())->where(['id' => $data['id']])->find();
            if (empty($order)) {
                $this->result([], 1, '派单任务不存在');
            }
            $post = [
                'getaddress' => $data['reAddress'] ?? '',
                'address' => $data['address'] ?? '',
                'lat' => $data['lat'] ?? '',
                'lon' => $data['lon'] ?? '',
            ];
            $url = 'https://apis.map.qq.com/ws/geocoder/v1';
            try {
                $result = api_curl($url, ['location' => $data['lat'] . ',' . $data['lon'], 'key' => 'KHMBZ-ADFKZ-H2IXE-TUFHJ-RR4LV-N7F4D', 'poi_options' => 'radius=50;policy=5']);
                $post['province'] = $result['result']['ad_info']['province'] ?? '';
                $post['city'] = $result['result']['ad_info']['city'] ?? '';
                $post['area'] = $result['result']['ad_info']['district'] ?? '';
            } catch (\Exception $e) {
                $this->result([], 1, $e->getMessage());
            }
            $message = [];
            $model = new Business();
            //************************** */
            //附近选址
            // $filed = 'ROUND(6378.138*2*ASIN(SQRT(POW(SIN((' . $data['lat'] . '*PI()/180-lat*PI()/180)/2),2)+COS(' . $data['lat'] . '*PI()/180)*COS(lat*PI()/180)*POW(SIN((' . $data['lon'] . '*PI()/180-lon*PI()/180)/2),2)))*100)/100 AS dist';
            // $havemendian = (new Business())
            //     ->field('id,name,' . $filed)
            //     ->where('id', '<>', $data['id'])
            //     ->where('type', $order['type'])
            //     ->order('dist asc')->having('dist <= 0.35')->where(['status' => [1, 2, 3]])->find();
            //更新订单状态
            if ($order['schedule'] == 1) {
                $post['schedule'] = 2;
            }
            // if ($order['schedule'] == 2 && ($order['contract'] == 2 || $order['ordertype'] == 3) && empty($havemendian)) {
            //     $post['schedule'] = 3;
            //     $post['status'] = 2;
            //     $message[] = [
            //         'orderid' => $order['id'],
            //         'user_id' =>  $order['suid'],
            //         'ouser_id' => 0,
            //         'status' => $order['schedule'],
            //         'endstatus' => $post['schedule'],
            //         'text' => '您的售后单选址完成，请填写信息'
            //     ];
            // }
            // $ishavesc = (new Sucai())->where(['isdefault' => 0, 'orderid' => $order['id'], 'type' => 1])->find();
            // $xuan = [
            //     'isdefault' => 0,
            //     'user_id' => 0,
            //     'orderid' => $order['id'],
            //     'type' => 1,
            //     'pinpai' => $order['type'],
            //     'images4' => json_encode($data['images4'] ?? [], true),
            //     'images10' => json_encode($data['images10'] ?? [], true),
            //     'video1' => json_encode($data['video1'] ?? [], true),
            //     'sctype' => 3,
            //     'status' => 2,
            //     'finished' => date('Y-m-d H:i:s')
            // ];
            //附近门店判断结束
            //************************** */
            $res = $model->allowfield(true)->save($post, ['id' => $data['id']]);
            if ($res) {
                $this->result([], 0, '提交成功');
            }
            $this->result([], 1, '提交失败，请重试');
        }
    }

    public function signexcel()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
                'newdata' => 'require'
            ], [
                'id.require' => 'id不能为空',
                'newdata.require' => '数据不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $signexcel = (new Signexcel())->where(['id' => $data['id']])->find();
            if (empty($signexcel)) {
                $this->result([], 1, '数据不存在');
            }
            if ($signexcel['status'] == 2) {
                $this->result([], 1, '数据已审核，不可变更');
            }
            $yeardays = $signexcel['yeardays'];
            $time = strtotime($yeardays);
            $firstmonth = date('Y-m-01', $time);
            $lastmonth = date('Y-m-01', strtotime('+1 month', $time));
            $alldays = (strtotime($lastmonth) - strtotime($firstmonth)) / 86400;
            if ($alldays > 31) {
                $alldays = 31;
            }
            $nowdays = 0;
            foreach ($data['newdata'] as $newdata) {
                $datess = explode('~', $newdata['date']);
                if (count($datess) == 1) {
                    $datess[0] = trim($datess[0]);
                    if (!is_numeric($datess[0])) {
                        $this->result([], 1, $newdata['date'] . '日期错误,日期必须是整数');
                    }
                } elseif (count($datess) == 2) {
                    $datess[0] = trim($datess[0]);
                    if (!is_numeric($datess[0])) {
                        $this->result([], 1, $newdata['date'] . '开始日期错误,日期必须是整数');
                    }
                    $datess[1] = trim($datess[1]);
                    if (!is_numeric($datess[1])) {
                        $this->result([], 1, $newdata['date'] . '结束日期错误,日期必须是整数');
                    }
                } else {
                    $this->result([], 1, $newdata['date'] . '日期范围错误');
                }
                $nowdays += (int)$newdata['days'];
            }
            if ($nowdays > $alldays) {
                $this->result([], 1, '实施天数总和不能超过当月天数，请确保日期范围填写正确');
            }
            $save = [
                'newdata' => json_encode($data['newdata'], true),
                'status' => 1
            ];
            $res = (new Signexcel())->where(['id' => $data['id']])->update($save);
            if ($res) {
                $this->result([], 0, '提交成功，请等待审核');
            }
            $this->result([], 1, '提交失败，请重试');
        } else {
            getexcels($this->request->user, strtotime("-1 month"));
            $list = (new Signexcel());
            $data = $this->request->get();
            $page = $data['page'] ?? 1;
            $limit =  $data['limit'] ?? 10;
            $results = (new Signexcel())->limit($limit)->page($page)->order('yeardays desc')->where(['user_id' => $this->request->user_id])->select();
            foreach ($results as $rowlsm) {
                $olddata = json_decode($rowlsm['olddata'], true) ?? [];
                foreach ($olddata as $k => &$row) {
                    $row['orderid'] = $row['orderid'] ?? 0;
                    $mianji = '';
                    if (!empty($row['orderid'])) {
                        $weikuan = '';
                        $business = (new Business())->where(['id' => $row['orderid']])->select();
                        foreach ($business as $bus) {
                            $wk = '';
                            switch ($bus['weikuan']) {
                                case '1':
                                    $wk = '未回款';
                                    break;
                                case '2':
                                    $wk = '部分回款';
                                    break;
                                case '3':
                                    $wk = '全部回款';
                                    break;
                                default:
                                    $wk = '未知';
                                    break;
                            }
                            if ($bus['weikuanstatus'] == 2) {
                                $wk = $wk . '(待审核)';
                            }
                            if (empty($weikuan)) {
                                $weikuan = $wk;
                            } else {
                                $weikuan = $weikuan . '、' . $wk;
                            }
                        }
                        $row['weikuan'] = $weikuan;
                        if (empty($mianji)) {
                            $fg = '';
                        } else {
                            $fg = '、';
                        }
                        if ($bus['ordertype'] != 2 && $bus['ordertype'] != 12) {
                            if (!empty($bus['mianji']) && $bus['mianji'] == 2) {
                                $mianji = $mianji . $fg . '60-79m²';
                            }
                            if (!empty($bus['mianji']) && $bus['mianji'] == 3) {
                                $mianji = $mianji . $fg . '80m²及以上';
                            }
                        }
                    }
                    $row['areas'] = $mianji;
                }
                $rowlsm['olddata'] = $olddata;
                $newdata = json_decode($rowlsm['newdata'], true) ?? [];
                foreach ($newdata as &$row) {
                    $row['orderid'] = $row['orderid'] ?? 0;
                    $mianji = '';
                    if (!empty($row['orderid'])) {
                        $weikuan = '';
                        $business = (new Business())->where(['id' => $row['orderid']])->select();
                        foreach ($business as $bus) {
                            $wk = '';
                            switch ($bus['weikuan']) {
                                case '1':
                                    $wk = '未回款';
                                    break;
                                case '2':
                                    $wk = '部分回款';
                                    break;
                                case '3':
                                    $wk = '全部回款';
                                    break;
                                default:
                                    $wk = '未知';
                                    break;
                            }
                            if ($bus['weikuanstatus'] == 2) {
                                $wk = $wk . '(待审核)';
                            }
                            if (empty($weikuan)) {
                                $weikuan = $wk;
                            } else {
                                $weikuan = $weikuan . '、' . $wk;
                            }
                        }
                        $row['weikuan'] = $weikuan;
                        if (empty($mianji)) {
                            $fg = '';
                        } else {
                            $fg = '、';
                        }
                        if ($bus['ordertype'] != 2 && $bus['ordertype'] != 12) {
                            if (!empty($bus['mianji']) && $bus['mianji'] == 2) {
                                $mianji = $mianji . $fg . '60-79m²';
                            }
                            if (!empty($bus['mianji']) && $bus['mianji'] == 3) {
                                $mianji = $mianji . $fg . '80m²及以上';
                            }
                        }
                    }
                    $row['areas'] = $mianji;
                }
                $rowlsm['newdata'] = $newdata;
                $rowlsm['headrs'] = ['日期', '组别', '打卡地址', '客户', '考勤类型', '实施天数', '回款情况', '面积', '店铺信息', '照片违规', '迟到(次)', '早退(次)', '缺卡(次)', '旷工/休假(次)'];
                $rowlsm['headrs_sub'] = ['日期', '组别[不可修改]', '客户', '考勤类型', '实施天数[自动计算]', '面积[关闭修改]'];
                $rowlsm['zhongexc'] = $olddata;
                if ($rowlsm['status'] == 2) {
                    $rowlsm['zhongexc'] = $newdata;
                }
            }
            $this->result($results, 0, '操作成功');
        }
    }

    public function getannous()
    {
        $id  = $this->request->get('id/d', 0);
        $row = (new Annous())->where('id', $id)->find() ?? [];
        if ($row) {
            $row['fujian'] = json_decode($row['fujian'], true) ?? [];
            $row['fujian1'] = json_decode($row['fujian1'], true) ?? [];
            $row['fujian2'] = json_decode($row['fujian2'], true) ?? [];
            $types = explode(',', $row['type']);
            $typelist = [];
            foreach ($types as $k => $types) {
                $typelist[] = (int)$types;
            }
            $row['typelist'] = $typelist;
            $readed = (new Annouslog())->where(['user_id' => $this->request->user_id, 'annousid' => $row['id']])->find();
            if (empty($readed)) {
                (new Annouslog())->allowfield(true)->save(['user_id' => $this->request->user_id, 'annousid' => $row['id']]);
            }
        }
        $supertypelist = []; //人员类型
        $supertype = config('config.typepeople');
        foreach ($supertype as $k => $v) {
            if ($this->request->user['type'] == 4 || $this->request->user['type'] == 5) {
                $supertypelist[] = ['id' => $k, 'name' => $v];
            }
            if ($this->request->user['type'] == 10 && $k == 11) {
                $supertypelist[] = ['id' => $k, 'name' => $v];
            }
            if ($this->request->user['type'] == 12 && $k == 13) {
                $supertypelist[] = ['id' => $k, 'name' => $v];
            }
            if ($this->request->user['type'] == 14 && $k == 15) {
                $supertypelist[] = ['id' => $k, 'name' => $v];
            }
            if ($this->request->user['type'] == 16 && $k == 17) {
                $supertypelist[] = ['id' => $k, 'name' => $v];
            }
            if ($this->request->user['type'] == 18 && $k == 19) {
                $supertypelist[] = ['id' => $k, 'name' => $v];
            }
            if ($this->request->user['type'] == 20 && $k == 21) {
                $supertypelist[] = ['id' => $k, 'name' => $v];
            }
        }
        $row['supertypelist'] = $supertypelist;
        $this->result($row, 0, '获取成功');
    }

    public function superannous()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'title' => 'require',
                'type' => 'require'
            ], [
                'title.require' => '标题不能为空',
                'type.require' => '查看人员类型不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $type = $data['type'];
            $data['type'] = implode(',', $data['type']);
            $data['fujian'] = json_encode($data['fujian'] ?? [], true) ?? '';
            $data['fujian1'] = json_encode($data['fujian1'] ?? [], true) ?? '';
            $data['fujian2'] = json_encode($data['fujian2'] ?? [], true) ?? '';
            $message = [];
            Db::startTrans();
            try {
                if (!empty($data['id'])) {
                    (new Annous())->allowfield(true)->save($data, ['id' => $data['id']]);
                } else {
                    $data['user_id'] = $this->request->user_id;
                    $data['id'] = (new Annous())->strict(false)->insertGetId($data);
                }
                if (!empty($data['message']) && $data['message'] == 1) {
                    $users = (new Users())->where(['type' => $type, 'del' => 1])->column('id') ?? [];
                    foreach ($users as $user) {
                        $message[] = [
                            'type' => 8,
                            'orderid' => $data['id'],
                            'user_id' =>  $user,
                            'ouser_id' => 0,
                            'status' => 1,
                            'endstatus' => 1,
                            'text' => '您有新的通知或公告待阅读！',
                            'yue' => 2,
                        ];
                    }
                }
                if (count($message) > 0) {
                    (new Messages())->allowfield(true)->saveAll($message);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, $e->getMessage());
            }
            $this->result([], 0, '操作成功');
        } else {
            $list = (new Annous());
            $data = $this->request->get();
            $page = $data['page'] ?? 1;
            $where = [];
            if (!empty($data['title'])) {
                $where[] = ['title', 'like', '%' . $data['title'] . '%'];
            }
            if (!empty($data['leixin'])) {
                $where[] = ['leixin', '=', $data['leixin']];
            }
            if (!empty($data['fltype'])) {
                $where[] = ['fltype', '=', $data['fltype']];
            }
            if (!empty($data['isread'])) {
                $readed = (new Annouslog())->where(['user_id' => $this->request->user_id])->column('annousid') ?? [];
                if ($data['isread'] == 1) {
                    $where[] = ['fltype', 'in', $readed];
                } else {
                    $where[] = ['fltype', 'not in', $readed];
                }
            }
            if ($this->request->user['type'] == 4 || $this->request->user['type'] == 5) {
                if (!empty($data['type'])) {
                    $where[] = Db::raw("FIND_IN_SET('" . $data['type'] . "', type)");
                }
            } elseif ($this->request->user['type'] == 10) {
                if ($data['subcurrent'] == 1) {
                    $where[] = Db::raw("FIND_IN_SET('" . $this->request->user['type'] . "', type)");
                    $where[] = ['enddates', '>= time', date('Y-m-d')];
                } else {
                    $where[] = Db::raw("FIND_IN_SET('11', type)");
                }
            } elseif ($this->request->user['type'] == 12) {
                if ($data['subcurrent'] == 1) {
                    $where[] = Db::raw("FIND_IN_SET('" . $this->request->user['type'] . "', type)");
                    $where[] = ['enddates', '>= time', date('Y-m-d')];
                } else {
                    $where[] = Db::raw("FIND_IN_SET('13', type)");
                }
            } elseif ($this->request->user['type'] == 14) {
                if ($data['subcurrent'] == 1) {
                    $where[] = Db::raw("FIND_IN_SET('" . $this->request->user['type'] . "', type)");
                    $where[] = ['enddates', '>= time', date('Y-m-d')];
                } else {
                    $where[] = Db::raw("FIND_IN_SET('15', type)");
                }
            } elseif ($this->request->user['type'] == 16) {
                if ($data['subcurrent'] == 1) {
                    $where[] = Db::raw("FIND_IN_SET('" . $this->request->user['type'] . "', type)");
                    $where[] = ['enddates', '>= time', date('Y-m-d')];
                } else {
                    $where[] = Db::raw("FIND_IN_SET('17', type)");
                }
            } elseif ($this->request->user['type'] == 18) {
                if ($data['subcurrent'] == 1) {
                    $where[] = Db::raw("FIND_IN_SET('" . $this->request->user['type'] . "', type)");
                    $where[] = ['enddates', '>= time', date('Y-m-d')];
                } else {
                    $where[] = Db::raw("FIND_IN_SET('19', type)");
                }
            } elseif ($this->request->user['type'] == 20) {
                if ($data['subcurrent'] == 1) {
                    $where[] = Db::raw("FIND_IN_SET('" . $this->request->user['type'] . "', type)");
                    $where[] = ['enddates', '>= time', date('Y-m-d')];
                } else {
                    $where[] = Db::raw("FIND_IN_SET('21', type)");
                }
            } else {
                $where[] = Db::raw("FIND_IN_SET('" . $this->request->user['type'] . "', type)");
                $where[] = ['enddates', '>= time', date('Y-m-d')];
            }
            $sort = ['dates' => 'desc'];
            if (!empty($data['sort'])) {
                $sort = ['id' => 'desc'];
            }
            $typearr = config('config.typepeople');
            $list = $list->where($where)->order($sort)->page($page)->select();
            $add = 1;
            if (in_array($this->request->user['type'], [4, 5])) {
                $add = 2;
            }
            if (in_array($this->request->user['type'], [10, 12, 14, 16, 18, 20])) {
                $add = 3;
            }
            foreach ($list as $row) {
                $readed = (new Annouslog())->where(['user_id' => $this->request->user_id, 'annousid' => $row['id']])->find();
                if (empty($readed)) {
                    $row['read'] = 1;
                } else {
                    $row['read'] = 2;
                }
                if ($row['user_id'] > 0) {
                    $row['user_name'] = (new Users())->where('id', $row['user_id'])->value('account') ?? '无';
                }
                $types = explode(',', $row['type']);
                $text = '';
                foreach ($types as $type) {
                    $text = $text . ' ' . $typearr[$type] ?? '';
                }
                $row['type_text'] = $text;
                $row['fujian'] = json_decode($row['fujian'], true) ?? [];
                $row['fujian1'] = json_decode($row['fujian1'], true) ?? [];
                $row['fujian2'] = json_decode($row['fujian2'], true) ?? [];
                $types = explode(',', $row['type']);
                $typelist = [];
                foreach ($types as $k => $types) {
                    $typelist[] = (int)$types;
                }
                $row['typelist'] = $typelist;
                //可编辑按钮控制
                $row['isedit'] = 1;
                if ($this->request->user['type'] == 4 || $this->request->user['type'] == 5) {
                    $row['isedit'] = 2;
                }
                if ($this->request->user['type'] == 10 && $row['type'] == 11) {
                    $row['isedit'] = 2;
                }
                if ($this->request->user['type'] == 12 && $row['type'] == 13) {
                    $row['isedit'] = 2;
                }
                if ($this->request->user['type'] == 14 && $row['type'] == 15) {
                    $row['isedit'] = 2;
                }
                if ($this->request->user['type'] == 16 && $row['type'] == 17) {
                    $row['isedit'] = 2;
                }
                if ($this->request->user['type'] == 18 && $row['type'] == 19) {
                    $row['isedit'] = 2;
                }
            };
            $supertypelist = []; //人员类型
            $supertype = config('config.typepeople');
            foreach ($supertype as $k => $v) {
                if ($this->request->user['type'] == 4 || $this->request->user['type'] == 5) {
                    $supertypelist[] = ['id' => $k, 'name' => $v];
                }
            }
            $this->result(['data' => $list, 'typepeople' => $supertypelist, 'add' => $add], 0, '获取成功');
        }
    }

    public function userstatus()
    {
        if ($this->request->user['status'] != 2) {
            $this->result([], 1, '待单状态无法切换');
        }
        $data = $this->request->post();
        $message = [];
        $guanli = (new Users())->where(['type' => [4, 5], 'del' => 1, 'look' => 1])->select();
        foreach ($guanli as $guanlis) {
            $message[] = [
                'orderid' => 0,
                'user_id' =>  $guanlis['id'],
                'ouser_id' => 0,
                'status' => 1,
                'endstatus' => 1,
                'text' => '督导' . $this->request->user['account'] . '切换待单状态！',
                'yue' => 2,
            ];
        }
        if (!empty($data['lat']) && !empty($data['lng'])) {
            $key = env('map.key');
            $url = 'https://restapi.amap.com/v3/geocode/regeo';
            try {
                $result = api_curl($url, ['location' => $data['lng'] . ',' . $data['lat'], 'key' => $key, 'extensions' => 'all']);
                $data['address'] = $result['regeocode']['formatted_address'] ?? '';
            } catch (\Exception $e) {
                $this->result([], 1, $e->getMessage());
            }
        }
        Db::startTrans();
        try {
            (new Userstatus())->UserStatus_m($this->request->user_id, 2, 0, 1, $data['lat'] ?? 0, $data['lng'] ?? 0, $data['address'] ?? "");
            if (count($message) > 0) {
                (new Messages())->allowfield(true)->saveAll($message);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->result([], 1, $e->getMessage());
        }
        $this->result([], 0, '操作成功');
    }

    public function getdaidan()
    {
        $data = $this->request->get();
        $page = $data['page'] ?? 1;
        $limit =  $data['limit'] ?? 10;
        $page = (int)$page;
        $limit = (int)$limit;
        $results = (new Users())->limit($limit)->page($page)->order('id desc')->where(['del' => 1, 'status' => 1, 'type' => 2, 'fangjia' => 1])->select();
        foreach ($results as $row) {
            $row['userstatus'] = (new Userstatus())->where(['user_id' => $row['id'], 'orderid' => 0, 'type' => 2])->order('id desc')->find();
        }
        $this->result($results, 0, '操作成功');
    }

    public function savezhaopai()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'type' => 'require|in:1,2',
                'images' => 'require',
                'orderid' => 'require',
                'lat' => 'require',
                'lng' => 'require',
            ], [
                'type.require' => '文件类型不能为空',
                'type.in' => '文件类型不正确',
                'orderid.require' => '门店ID不能为空',
                'images.require' => '文件不能为空',
                'lat.require' => '坐标不能为空，请打开定位',
                'lng.require' => '坐标不能为空，请打开定位',

            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            //数据核验
            if (!is_array($data['images'])) {
                $this->result([], 1, '数据类型错误，请重试');
            }
            if (count($data['images']) < 1) {
                $this->result([], 1, '必须传至少一个文件');
            }
            $business = (new Business())->where(['id' => $data['orderid'], 'bicloses' => [1, 2, 3]])->find();
            if (empty($business)) {
                $this->result([], 1, '调查信息不存在或已不处于调查状态');
            }
            $post = [
                'user_id' => $this->request->user_id,
                'type' => $data['type'] ?? 0,
                'orderid' => $data['orderid'] ?? 0,
                'images' => json_encode($data['images'], true),
                'lat' => $data['lat'] ?? 0,
                'lng' => $data['lng'] ?? 0,
                'address' => $data['address'] ?? '',
                'status' => 1,
            ];
            if (empty($data['zpid'])) {
                $zhaopaiid = (new Zhaopai())->where(['user_id' => $this->request->user_id, 'type' => $data['type'], 'status' => 1])->value('id');
            } else {
                $zhaopaiid = $data['zpid'];
            }
            Db::startTrans();
            try {
                (new Business())->allowfield(true)->save(['bicloses' => 3], ['id' => $data['orderid']]);
                if (empty($zhaopaiid)) {
                    (new Zhaopai())->allowfield(true)->save($post);
                } else {
                    (new Zhaopai())->allowfield(true)->save($post, ['id' => $zhaopaiid]);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, $e->getMessage());
            }
            $this->result([], 0, '操作成功');
        }
    }

    public function saveFile()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'type' => 'require|in:1,2,3',
                'title' => 'require',
                'url' => 'require',
            ], [
                'type.require' => '文件类型不能为空',
                'type.in' => '文件类型不正确',
                'title.require' => '文件标题不能为空',
                'url.require' => '文件不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            //数据核验
            if (!is_array($data['url'])) {
                $this->result([], 1, '数据类型错误，请重试');
            }
            if (count($data['url']) < 1) {
                $this->result([], 1, '必须传至少一个文件');
            }
            $post = [
                'user_id' => $this->request->user_id,
                'type' => $data['type'],
                'title' => $data['title'],
                'url' => json_encode($data['url'], true)
            ];
            Db::startTrans();
            try {
                if (empty($data['id'])) {
                    (new Wenjian())->allowfield(true)->save($post);
                } else {
                    (new Wenjian())->allowfield(true)->save($post, ['id' => $data['id']]);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, $e->getMessage());
            }
            $this->result([], 0, '操作成功');
        } else {
            $data = $this->request->get();
            $page = $data['page'] ?? 1;
            $limit =  $data['limit'] ?? 10;
            $page = (int)$page;
            $limit = (int)$limit;
            $results = (new Wenjian())->limit($limit)->page($page)->order('id desc')->where('user_id', $this->request->user_id)->select();
            foreach ($results as $result) {
                $result['url'] = json_decode($result['url'], true);
            }
            $this->result($results, 0, '操作成功');
        }
    }

    public function pinfen()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'list' => 'require'
            ], [
                'list.require' => '数据不能为空'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $ziwolist = [];
            foreach ($data['list'] as $row) {
                $ziwo = (float)($row['ziwo'] ?? 0);
                if ($ziwo > $row['branch']) {
                    $this->result([], 1, '自我评分不能大于权重分');
                }
                $ziwolist[$row['id']] = $ziwo;
            }
            $kaoke = (new Users())->where('id', $this->request->user_id)->value('kaoke') ?? '';
            $kaokedata = json_decode($kaoke, true) ?? [];
            $kaokedata['ziwo'] = $ziwolist;
            $json = json_encode($kaokedata, true);
            Db::startTrans();
            try {
                (new Users())->where('id', $this->request->user_id)->update(['kaoke' => $json]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, $e->getMessage());
            }
            $this->result([], 0, '操作成功');
        } else {
            $list = (new Kaoke())->order('type asc')->select();
            $kaoke = (new Users())->where('id', $this->request->user_id)->value('kaoke') ?? '';
            $kaokedata = json_decode($kaoke, true) ?? [];
            $zongfen = 0;
            $ziwofen = 0;
            foreach ($list as $row) {
                $row['ziwo'] =  $kaokedata['ziwo'][$row['id']] ?? '';
                $zongfen += floor($row['branch'] * 100) / 100;
                $ziwofen += floor($row['ziwo'] * 100) / 100;
            }
            $this->result(['list' => $list, 'zongfen' => floor($zongfen * 100) / 100, 'ziwofen' => floor($ziwofen * 100) / 100], 0, '获取成功');
        }
    }


    public function getreads()
    {
        if ($this->request->isGet()) {
            $data = $this->request->get();
            $validate = new Validate([
                'id' => 'require'
            ], [
                'id.require' => 'ID不能为空'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $type = 2;
            if ($this->request->user['type'] == 4 || $this->request->user['type'] == 5) {
                $type = 1;
            }
            Db::startTrans();
            try {
                Redis::setex('getddreads' . $this->request->user_id . $data['id'], 3, 3);
                (new Liaotian())->where(['reimbursid' => $data['id'], 'type' => $type])->update(['message' => 2]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, $e->getMessage());
            }
            $this->result([], 0, '获取成功');
        }
    }

    public function liaotian()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
                'content' => 'require',
            ], [
                'id.require' => 'ID不能为空',
                'content.require' => '信息不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $type = 1;
            if ($this->request->user['type'] == 4 || $this->request->user['type'] == 5) {
                $touser_id = (new Reimburs())->where('id', $data['id'])->value('user_id') ?? 0;
                $type = 2;
                if ($touser_id == $this->request->user_id) {
                    $this->result([], 1, '该订单你已经是审核人员了，无需咨询');
                }
            } else {
                $touser_id = (new Users())->whereNotNull('openid')->where(['type' => 4, 'look' => 1, 'del' => 1])->column('id') ?? [];
                $touser_id = implode(',', $touser_id);
                //验权
                $reimbursuser_id = (new Reimburs())->where('id', $data['id'])->value('user_id') ?? 0;
                if ($reimbursuser_id != $this->request->user_id) {
                    $this->result([], 1, '当前非本人报销单,无发信息权限');
                }
            }
            $save = [
                'id' => 0,
                'user_id' => $this->request->user_id,
                'touser_id' => $touser_id,
                'reimbursid' => $data['id'],
                'content' => $data['content'],
                'type' => $type,
                'isde' => 1,
                'created' => date('Y-m-d H:i:s')
            ];
            Db::startTrans();
            try {
                $save['id'] = (new Liaotian())->strict(false)->insertGetId($save);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, $e->getMessage());
            }
            $message = [
                "id" => $save['id'],
                "content" => $save['content'],
                "type" => 1,
                "pic" => "/static/logo.png"
            ];
            $this->result($message, 0, '发送成功');
        } else {
            $data = $this->request->get();
            $id = $data['id'] ?? 0;
            $page = $data['page'] ?? 1;
            $limit = $data['limit'] ?? 20;
            $page = (int)$page;
            $limit = (int)$limit;
            $lastid = $data['lastid'] ?? 0;;
            $list = (new Liaotian())->where(['reimbursid' => $id, 'isdel' => 1])->page($page)->limit($limit)->order(['id' => 'desc']);
            if ($lastid > 0) {
                $list = $list->where('id', '>', $lastid);
            }
            $list = $list->select();
            $message = [];
            foreach ($list as $k => $row) {
                $type = 0; //1自己消息 2接收消息
                if ($this->request->user['type'] == 4 || $this->request->user['type'] == 5) {
                    if ($row['type'] == 2) {
                        $type = 1;
                    } else {
                        $type = 2;
                    }
                } else {
                    if ($row['type'] == 2) {
                        $type = 2;
                    } else {
                        $type = 1;
                    }
                }
                $message[] = [
                    "id" => $row['id'],
                    "content" => $row['content'],
                    "type" => $type,
                    "pic" => "/static/logo.png"
                ];
            }
            $message = array_reverse($message);
            $this->result($message, 0, '获取成功');
        }
    }

    public function annous()
    {
        if ($this->request->isPost()) {
            $leixin = $this->request->post('leixin/d', 0);
            $yuedued = (new Annous());
            $sonstype = [0, 1, 2];
            if ($this->request->user['type'] == 2) {
                $sonstype = [0, $this->request->user['sonstype']];
            }
            $yuedued = $yuedued->where(['sonstype' => $sonstype]);
            if (!empty($leixin)) {
                $yuedued = $yuedued->where(['leixin' => $leixin]);
            }
            if ($this->request->user['type'] == 4 || $this->request->user['type'] == 5) {
                $yuedued = $yuedued->whereTime('enddates', '>=', date('Y-m-d'))
                    ->field('id,dates,content,title')->order('id desc')->column('id') ?? [];
            } else {
                $yuedued = $yuedued->whereTime('enddates', '>=', date('Y-m-d'))
                    ->field('id,dates,content,title')->order('id desc')->where("FIND_IN_SET (" . $this->request->user['type'] . ",type)")->column('id') ?? [];
            }

            $save = [];
            foreach ($yuedued as $key => $list) {
                $readed = (new Annouslog())->where(['user_id' => $this->request->user_id, 'annousid' => $list])->find();
                if (empty($readed)) {
                    $save[] = ['user_id' => $this->request->user_id, 'annousid' => $list];
                }
            }
            if (count($save) <= 0) {
                $this->result([], 0, '操作成功');
            }
            $res = (new Annouslog())->allowfield(true)->saveAll($save);
            if ($res) {
                $this->result([], 0, '操作成功');
            }
            $this->result([], 1, '操作失败');
        } else {
            $type = $this->request->get('type/d', 0);
            $leixin = $this->request->get('leixin/d', 1);
            if (empty($type)) {
                $readed = (new Annouslog())->where(['user_id' => $this->request->user_id])->column('annousid') ?? [];
            } else {
                $readed = [];
            }
            $sonstype = [0, 1, 2];
            if ($this->request->user['type'] == 2) {
                $sonstype = [0, $this->request->user['sonstype']];
            }
            if ($this->request->user['type'] == 4 || $this->request->user['type'] == 5) {
                $result = (new Annous())->where(['sonstype' => $sonstype])->where(['leixin' => $leixin])->whereNotIn('id', $readed)->whereTime('enddates', '>=', date('Y-m-d'))
                    ->field('id,dates,content,title,fujian,fujian1,fujian2,fltype')->order('dates desc')->select();
            } else {
                $result = (new Annous())->where(['sonstype' => $sonstype])->where(['leixin' => $leixin])->whereNotIn('id', $readed)->whereTime('enddates', '>=', date('Y-m-d'))
                    ->field('id,dates,content,title,fujian,fujian1,fujian2,fltype')->order('dates desc')->where("FIND_IN_SET (" . $this->request->user['type'] . ",type)")->select();
            }
            foreach ($result as $row) {
                $row['fujian'] = json_encode($row['fujian'], true);
                $row['fujian1'] = json_decode($row['fujian1'], true);
                $row['fujian2'] = json_decode($row['fujian2'], true);
                $count = (new Annouslog())->where(['user_id' => $this->request->user_id, 'annousid' => $row['id']])->count();
                if ($count == 0) {
                    $row['title'] = '[未读]' . $row['title'];
                }
            }
            $this->result($result, 0, '获取成功');
        }
    }

    public function myleave()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'duration' => 'require',
                'type' => 'require',
                'startime' => 'require',
                'endtime' => 'require',
            ], [
                'duration.require' => '休息时长计算失败，请重试',
                'type.require' => '类型不能为空',
                'startime.require' => '开始时间不能为空',
                'endtime.require' => '结束时间不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $day = abs((strtotime($data['startime']) -  strtotime($data['endtime'])) / 86400);
            if ($data['type'] == 1) {
                if (empty($data['startype']) || empty($data['endtype'])) {
                    $this->result([], 1, '请选择具体时间类型');
                }
                if ($data['startype'] == 1) {
                    $day += 0.5;
                }
                if ($data['endtype'] == 2) {
                    $day += 0.5;
                }
            } else {
                $day += 1;
                $data['startype'] = 0;
                $data['endtype'] = 0;
            }
            if ($day != $data['duration']) {
                $this->result([], 1, '请假时长验证失败');
            }
            $post = [
                'user_id' => $this->request->user_id,
                'type' => $data['type'],
                'startime' => $data['startime'],
                'startype' =>  $data['startype'] ?? 0,
                'endtime' => $data['endtime'],
                'endtype' =>  $data['endtype'] ?? 0,
                'duration' => $data['duration'],
                'remark' => $data['remark'] ?? '',
                'status' => 1,
                'created' => date('Y-m-d H:i:s')
            ];
            Db::startTrans();
            try {
                if (empty($data['id'])) {
                    (new Leave())->allowfield(true)->save($post);
                } else {
                    (new Leave())->allowfield(true)->save($post, ['id' => $data['id']]);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, $e->getMessage());
            }
            $this->result([], 0, '提交成功');
        }
    }

    public function leavelist()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require'
            ], [
                'id.require' => '关联订单不能为空'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $order = (new Leave())->where(['id' => $data['id'], 'user_id' => $this->request->user_id, 'status' => 1])->find();
            if (empty($order)) {
                $this->result([], 1, '申请不存在或处于不可撤销状态');
            }
            //保存
            Db::startTrans();
            try {
                (new Leave())->where(['id' => $order['id'], 'status' => 1])->update(['status' => 4]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, $e->getMessage());
            }
            $this->result([], 0, '操作成功');
        } else {
            $data = $this->request->get();
            $list = (new Leave())->order(['created' => 'desc']);
            $page = $data['page'] ?? 1;
            $page = (int)$page;
            $list = $list->where('user_id', $this->request->user_id);
            $list = $list->limit(10)->page($page)->select();
            $this->result($list, 0, '获取成功');
        }
    }

    public function postsignstatus()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'status' => 'require',
        ], [
            'id.require' => 'ID不能为空',
            'status.require' => '状态不能为空',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $order = (new Signlog())->where(['id' => $data['id']])->find();
        if (empty($order)) {
            $this->result([], 1, '打卡记录不存在不存在');
        }
        if ($order['status'] != 1) {
            $this->result([], 1, '打卡记录不属于操作状态');
        }
        if ($data['status'] == 4) {
            if ($order['user_id'] != $this->request->user_id) {
                $this->result([], 1, '非打卡人不可操作撤销');
            }
        } else {
            if ($this->request->user['type'] != 4 && $this->request->user['type'] != 5) {
                $this->result([], 1, '无此操作权限');
            }
        }
        $post = [];
        if ($data['status'] == 2) {
            $sign = (new Sign())->where(['user_id' => $order['user_id'], 'yearday' => $order['yearday']])->find();
            if (!empty($sign)) {
                if ($order['monoraft'] == 1 && $sign['monstar'] == 2) {
                    $this->result([], 1, '上班卡已存在，请撤回或取消此次补卡');
                }
                if ($order['monoraft'] == 2 && $sign['aftstar'] == 2) {
                    $this->result([], 1, '下班卡已存在，请撤回或取消此次补卡');
                }
            }
            //上班卡
            if ($order['monoraft'] == 1) {
                $post['monstar'] = 2;
                $post['month_time'] = date('Y-m-d H:i:s');
            }
            //下班卡
            if ($order['monoraft'] == 2) {
                $post['aftstar'] = 2;
                $post['after_time'] = date('Y-m-d H:i:s');
            }
            $post['user_id'] = $order['user_id'] ?? 0;
            $post['orderid'] = $order['orderid'] ?? 0;
            $post['lat'] = $order['lat'] ?? 0;
            $post['lng'] = $order['lng'] ?? 0;
            $post['years'] = $order['years'] ?? 0;
            $post['yearday'] = $order['yearday'] ?? 0;
            $post['btaddress'] = $order['btaddress'] ?? '';
            $post['btname'] = $order['btname'] ?? '';
            $post['texts'] = $order['texts'] ?? '';
            $addresstext = '';
            if ($post['lat'] > 0 && $post['lng'] > 0) {
                $url = 'https://restapi.amap.com/v3/geocode/regeo';
                Redis::zAdd('getlatlonarrs' . $this->request->user_id, time(), $post['lng'] . ',' . $post['lat']);
                try {
                    $res = api_curl($url, ['location' => $post['lng'] . ',' . $post['lat'], 'key' => 'c400abfe779387dc8ded64d7db8dbbac', 'extensions' => 'base']);
                    if (!empty($res['regeocode']['addressComponent'])) {
                        if (empty($res['regeocode']['addressComponent']['city']) || is_array($res['regeocode']['addressComponent']['city'])) {
                            $city = $res['regeocode']['addressComponent']['province'] ?? '';
                        } else {
                            $city = $res['regeocode']['addressComponent']['city'] ?? '';
                        }
                        if (empty($res['regeocode']['addressComponent']['district']) || is_array($res['regeocode']['addressComponent']['district'])) {
                            $street  = '';
                        } else {
                            $street = $res['regeocode']['addressComponent']['district'] ?? '';
                        }
                        $addresstext = $city . $street;
                    }
                } catch (\Exception $e) {
                }
            }
            if (!empty($addresstext)) {
                $post['addresstext'] = $addresstext;
            }
        }
        Db::startTrans();
        try {
            (new Signlog())->allowfield(true)->save(['status' => $data['status']], ['id' => $order['id']]);
            if (!empty($post)) {
                if (!empty($sign)) {
                    (new Sign())->allowfield(true)->save($post, ['id' => $sign['id']]);
                } else {
                    (new Sign())->allowfield(true)->save($post);
                }
            }
            if ($data['status'] == 3) {
                (new Message())->allowfield(true)->save([
                    'type' => 1,
                    'orderid' => 0,
                    'user_id' =>  $order['user_id'],
                    'ouser_id' => 0,
                    'status' => 1,
                    'endstatus' => 0,
                    'text' => $order['yearday'] . '补卡申请被驳回!',
                    'yue' => 2
                ]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->result([], 1, $e->getMessage());
        }
        $this->result([], 0, '操作成功');
    }

    public function dingorxuan()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
                'list' => 'require|egt:0'
            ], [
                'id.require' => '订单ID不能为空',
                'list.require' => '数据参数错误',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $order = (new Business())->where(['id' => $data['id'], 'ordertype' => [2, 12]])->find();
            if (empty($order)) {
                $this->result([], 1, '订单不存在或非定店类型订单');
            }
            //数据核验
            if (!is_array($data['list'])) {
                $this->result([], 1, '数据类型错误，请重试');
            }
            if (count($data['list']) < 3) {
                $this->result([], 1, '数据数量错误,请刷新重试');
            }
            foreach ($data['list'] as $k => $list) {
                if (empty($list['mentou']) || empty($list['shipin'])) {
                    $this->result([], 1, '门头和视频信息不能为空');
                }
                if (empty($list['mentoutext']) || empty($list['shipintext'])) {
                    $this->result([], 1, '说明信息不能为空');
                }
                if (empty($list['lat']) || empty($list['lng'])) {
                    $this->result([], 1, '定位坐标信息为空，请重试');
                }
                if (empty($list['getaddress']) || empty($list['address'])) {
                    $this->result([], 1, '定位地标名称和详细名称不能为空');
                }
                if (count($list['mentou']) < 2) {
                    $this->result([], 1, '门头照片不能少于俩张');
                }
            }
            $dingorxuan = (new Dingorxuan())->where(['orderid' => $data['id'], 'user_id' => $this->request->user_id, 'status' => [1, 3]])->find();
            $post = [
                'orderid' => $data['id'],
                'user_id' => $this->request->user_id,
                'status' => 1,
                'datas' => json_encode($data['list'], true)
            ];
            Db::startTrans();
            try {
                if (empty($dingorxuan)) {
                    (new Dingorxuan())->allowfield(true)->save($post);
                } else {
                    (new Dingorxuan())->allowfield(true)->save($post, ['id' => $dingorxuan['id']]);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, $e->getMessage());
            }
            $this->result([], 0, '操作成功');
        } else {
            $orderid  = $this->request->get('orderid/d', 0);
            $result = (new Dingorxuan())->where(['orderid' => $orderid, 'user_id' => $this->request->user_id, 'status' => [1, 3]])->find();
            if ($result) {
                $result['datas'] = json_decode($result['datas'], true);
            }
            $this->result($result, 0, '获取成功');
        }
    }

    public function getmark()
    {
        $orderid  = $this->request->get('orderid/d', 0);
        $result = (new Biaoji())->order('id asc')->field('id,readdress,address')->where(['del' => 1, 'orderid' => $orderid, 'user_id ' => $this->request->user_id])->select();
        $this->result($result, 0, '获取成功');
    }

    public function delmark()
    {
        $id  = $this->request->get('id/d', 0);
        $result = (new Biaoji())->where(['id' => $id, 'user_id ' => $this->request->user_id])->update(['del' => 2]);
        if ($result) {
            $this->result([], 0, '操作成功');
        }
        $this->result([], 1, '操作失败');
    }

    public function deltag()
    {
        if ($this->request->isGet()) {
            $data = $this->request->get();
            $validate = new Validate([
                'id' => 'require',
                'index' => 'require|egt:0'
            ], [
                'id.require' => 'ID不能为空',
                'index.require' => '参数错误',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $biaoji = (new Biaoji())->where(['id' => $data['id']])->find();
            if (empty($biaoji)) {
                $this->result([], 1, '操作信息不存在');
            }
            $data['index'] = (int)$data['index'];
            $tags = json_decode($biaoji['tags'] ?? '', true) ?? [];
            if (!empty($tags[$data['index']])) {
                unset($tags[$data['index']]);
            }
            $tags = array_filter($tags);
            $tags = array_values($tags);
            $tags = json_encode($tags, true);
            //保存
            Db::startTrans();
            try {
                (new Biaoji())->allowfield(true)->save(['tags' => $tags], ['id' => $data['id']]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, $e->getMessage());
            }
            $this->result([], 0, '操作成功');
        }
    }

    public function addtags()
    {
        if ($this->request->isGet()) {
            $data = $this->request->get();
            $validate = new Validate([
                'id' => 'require',
                'tags' => 'require|length:1,10'
            ], [
                'id.require' => 'ID不能为空',
                'tags.require' => '标签内容不能为空',
                'tags.length' => '标签长不超过10个字',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $biaoji = (new Biaoji())->where(['id' => $data['id']])->find();
            if (empty($biaoji)) {
                $this->result([], 1, '编辑信息不存在');
            }
            $tags = json_decode($biaoji['tags'] ?? '', true) ?? [];
            $tags[] = $data['tags'];
            $tags = array_filter($tags);
            $tags = array_values($tags);
            $tags = json_encode($tags, true);
            //保存
            Db::startTrans();
            try {
                (new Biaoji())->allowfield(true)->save(['tags' => $tags], ['id' => $data['id']]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, $e->getMessage());
            }
            $this->result([], 0, '操作成功');
        }
    }

    public function getbiaoji()
    {
        $lon  = $this->request->get('lon/f', '0');
        $lat  = $this->request->get('lat/f', '0');
        $filed = 'ROUND(6378.138*2*ASIN(SQRT(POW(SIN((' . $lat . '*PI()/180-lat*PI()/180)/2),2)+COS(' . $lat . '*PI()/180)*COS(lat*PI()/180)*POW(SIN((' . $lon . '*PI()/180-lon*PI()/180)/2),2)))*100)/100 AS dist';
        $result = (new Biaoji())
            ->field('*,' . $filed)
            ->order('dist asc');
        $result = $result->having('dist <= 100');
        $result = $result->limit(50)->where('del', 1)->where('lat|lon', "<>", 0)->select();
        foreach ($result as $shop) {
            $shop['can'] = 1;
            if ($shop['user_id'] == $this->request->user_id) {
                $shop['can'] = 2;
            }
            $shop['km'] = $shop['dist'] . 'km';
            $shop['tags'] = json_decode($shop['tags'], true) ?? [];
            $shop['images'] = json_decode($shop['images'], true) ?? [];
            $shop['video'] = json_decode($shop['video'], true) ?? [];
            $shop['img'] = $shop['images'][0]['url'] ?? '';
            $shop['have'] = 0;
            $filed = 'ROUND(6378.138*2*ASIN(SQRT(POW(SIN((' . $shop['lat'] . '*PI()/180-lat*PI()/180)/2),2)+COS(' . $shop['lat'] . '*PI()/180)*COS(lat*PI()/180)*POW(SIN((' . $shop['lon'] . '*PI()/180-lon*PI()/180)/2),2)))*100)/100 AS dist';
            $business = (new Business())
                ->field('id,' . $filed)->having('dist <= 1.5')->where('ctype', 1)->where(['status' => [1, 2, 3]])->where('lat|lon', "<>", 0)->where('type', "not in", [1, 2])->select();
            $shop['have'] = count($business);
        }
        $this->result($result, 0, '获取成功');
    }

    public function addmark()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'reAddress' => 'require',
                'lat' => 'require|gt:0',
                'lon' => 'require|gt:0',
                'address' => 'require',
                'remark' => 'require',
                'images' => 'require'
            ], [
                'reAddress.require' => '定位地址不能为空',
                'lat.require' => '定位坐标不能为空',
                'lat.gt' => '坐标值必须大于0',
                'lon.require' => '定位坐标不能为空',
                'lon.gt' => '坐标值必须大于0',
                'address.require' => '详细地址不能唯恐',
                'remark.require' => '说明不能唯恐',
                'images.require' => '街景图片不能为空'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $post = [
                'orderid' => $data['orderid'] ?? 0,
                'readdress' => $data['reAddress'],
                'address' => $data['address'],
                'lat' => $data['lat'],
                'lon' => $data['lon'],
                'type' => $data['type'] ?? 1,
                'text' => $data['remark'],
                'images' => json_encode($data['images'] ?? [], true) ?? '',
                'video' => json_encode($data['video'] ?? [], true) ?? '',
            ];
            if (!empty($data['id'])) {
                $biaoji = (new Biaoji())->where(['id' => $data['id']])->find();
                if (empty($biaoji)) {
                    $this->result([], 1, '编辑信息不存在');
                }
            } else {
                $post['user_id'] = $this->request->user_id;
            }
            //保存
            Db::startTrans();
            try {
                if (empty($data['id'])) {
                    (new Biaoji())->allowfield(true)->save($post);
                } else {
                    (new Biaoji())->allowfield(true)->save($post, ['id' => $data['id']]);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, $e->getMessage());
            }
            $this->result([], 0, '操作成功');
        } else {
            $id = $this->request->get('id/d', 0);
            $biaoji = (new Biaoji())->where(['id' => $id])->find();
            if ($biaoji) {
                $biaoji['images'] = json_decode($biaoji['images'], true) ?? [];
                $biaoji['video'] = json_decode($biaoji['video'], true) ?? [];
            }
            $this->result($biaoji, 0, '获取成功');
        }
    }

    public function getdingyue()
    {
        if ($this->request->isGet()) {
            $data = $this->request->get();
            $validate = new Validate([
                'tmpid' => 'require',
                'code' => 'require',
            ], [
                'tmpid.require' => '模板不能为空',
                'code.require' => '微信授权不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $xcxopenid = $this->request->user['xcxopenid'];
            if (empty($xcxopenid)) {
                $this->result([], 1, '您暂未绑定微信，请重新登录绑定或联系管理员');
            }
            $config = config('wechat.');
            $app = Factory::miniProgram($config);
            try {
                $res = $app->auth->session($data['code']);
                if (empty($res['openid'])) {
                    $this->result([], 1, '订阅权限获取失败，请重试');
                }
                if ($res['openid'] != $xcxopenid) {
                    $res = (new Users())->where('id', $this->request->user_id)->update(['xcxopenid' => $res['openid'], 'template' =>  $template = json_encode([], true)]);
                    if ($res) {
                        $this->result([], 0, '由于当前授权消息与原绑定微信不一致，系统已重新绑定，原授权消息归零');
                    } else {
                        $this->result([], 1, '授权失败，请重试');
                    }
                }
            } catch (\Exception $e) {
                $this->result([], 1, $e->getError());
            }
            //获取微信已授权消息
            $template = $this->request->user['template'];
            $template = json_decode($template ?? '', true) ?? [];
            if (empty($template[$data['tmpid']])) {
                $template[$data['tmpid']]['number'] = 0;
            }
            $template[$data['tmpid']]['number'] += 1;
            $cishu = $template[$data['tmpid']]['number'] ?? 0;
            $template = json_encode($template, true);
            $res = (new Users())->where('id', $this->request->user_id)->update(['template' => $template]);
            if ($res) {
                $this->result([], 0, '授权成功，您当前剩余订阅通知次数' . $cishu . '次');
            }
            $this->result([], 1, '授权失败，请重试');
        }
    }

    /**
     * 用户登录
     * @return mixed|void
     */
    public function savexcxopen()
    {
        if (request()->isPost()) {
            // 获取参数
            $config = config('wechat.');
            $code = input('code');
            $app = Factory::miniProgram($config);
            try {
                $res = $app->auth->session($code);
                if (!empty($res['openid'])) {
                    (new Users())->where('id', $this->request->user_id)->update(['xcxopenid' => $res['openid']]);
                }
            } catch (\Exception $e) {
                $this->result([], 1, $e->getError());
            }
            $this->result([], 0, '操作成功');
        }
    }

    public function getuseraut()
    {
        $lists = [];
        $users = (new Users())->field('id,account as name,mobile')->where(['del' => 1, 'type' => 2])->select();
        foreach ($users as $user) {
            //坐标信息
            $revRange = Redis::zRevRange('getlatlonarrs' . $user['id'], 0, 1, true); // 返回分数从高到低排序的前10名及分数
            if (!empty($revRange[0])) {
                $score = Redis::zScore('getlatlonarrs' . $user['id'], $revRange[0]);
                if (!empty($score)) {
                    $latlon = explode(',', $revRange[0]);
                    if (count($latlon) >= 2) {
                        $text = '未知地址';
                        $getaddress = Redis::get('get_address' . $user['id'] . $revRange[0]);
                        if (!$getaddress) {
                            $url = 'https://restapi.amap.com/v3/geocode/regeo';
                            $res = api_curl($url, ['location' => $revRange[0], 'key' => 'c400abfe779387dc8ded64d7db8dbbac', 'extensions' => 'all']);
                            if (!empty($res['regeocode']['formatted_address'])) {
                                $text = $res['regeocode']['formatted_address'];
                                Redis::setex('get_address' . $user['id'] . $revRange[0], 1 * 86400, $text);
                            }
                        } else {
                            $text = $getaddress;
                        }

                        $lists[] = [
                            'id' => $user['id'],
                            'latitude' => $latlon[1] ?? 0,
                            'longitude' =>  $latlon[0] ?? 0,
                            'name' => $user['name'],
                            'label' => [
                                'borderRadius' => 5,
                                'bgColor' => '#ffffff',
                                'padding' => '5',
                                'content' => $user['name']
                            ],
                            // 'customCallout' => [
                            //     "display" => "BYCLICK",
                            //     "zIndex" => 9999999999
                            // ],
                            'width' => 1,
                            'height' => 1,
                            'anchor' => [
                                'x' => 0,
                                'y' => 0
                            ],
                            'iconPath' => '/static/sign.png',
                            'mobile' => $user['mobile'],
                            'address' => $text,
                            'times' => date('m-d H:i', $score)
                        ];
                    }
                }
            }
        }
        $last_names = array_column($lists, 'times');
        array_multisort($last_names, SORT_DESC, $lists);
        $this->result($lists, 0, '操作成功');
    }

    public function reimburstatus()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require'
            ], [
                'id.require' => '关联订单不能为空'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $order = (new Reimburs())->where(['id' => $data['id'], 'user_id' => $this->request->user_id, 'status' => 1])->find();
            if (empty($order)) {
                $this->result([], 1, '报销单不存在或处于不可撤销状态');
            }
            //保存
            Db::startTrans();
            try {
                (new Reimburs())->where(['id' => $order['id'], 'status' => 1])->update(['status' => 4]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, $e->getMessage());
            }
            $this->result([], 0, '操作成功');
        }
    }

    public function Reimburs()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'orderid' => 'require',
                'ordertype' => 'require|in:1,2,99,100',
                'datas' => 'require',
                'groups' => 'require',
            ], [
                'orderid.require' => '关联订单不能为空',
                'ordertype.require' => '订单类型不能为空',
                'ordertype.in' => '订单类型不正确',
                'datas.require' => '报销明细不能为空',
                'groups.require' => '分组类型不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            if ($data['ordertype'] == 100 && $this->request->user['yuzhi'] != 2) {
                $this->result([], 1, '预支前请联系经理开通预支通道');
            }
            if (!empty($data['orderid'])) {
                if (empty($data['name'])) {
                    $this->result([], 1, '客户姓名不能为空');
                }
                if (empty($data['address'])) {
                    $this->result([], 1, '地址不能为空');
                }
                if (empty($data['jobtype'])) {
                    $this->result([], 1, '工作类型不能为空');
                }
            }
            if (!is_array($data['datas']) || count($data['datas']) < 1) {
                $this->result([], 1, '报销明细数据未填写或格式错误，请重试');
            }
            if ($this->request->user['hjtz'] > 3) {
                $this->result([], 1, '邮寄通知超3次，无法提交报销，请联系管理员');
            }
            if ($data['ordertype'] == 1 && (count($data['arrnames']) > 0 || !empty($data['arrkd']) || (!empty($data['tableFlist']) && count($data['tableFlist'])  > 0))) {
                if (empty($data['arrkd']) || empty($data['tableFlist']) || count($data['tableFlist']) <= 0 || count($data['arrnames']) <= 0) {
                    $this->result([], 1, '请填写快递名称、上传快递单号图据和客户名');
                }
                //查询上次提交数据
                $qishu = date('Ym', strtotime('-1 month'));
                $uporder = (new Uploadtk())->where(['user_id' => $this->request->user_id, 'qishu' => $qishu])->find();
                $status = 0;
                if (empty($uporder) || $uporder['status'] == 3) {
                    $status = 1;
                } else {
                    $status = $uporder['status'];
                }
                $upsave = [
                    'user_id' => $this->request->user_id,
                    'qishu' => $qishu,
                    'kdorder' => $data['arrkd'],
                    'images' => json_encode($data['tableFlist'] ?? '', true),
                    'names'  =>  json_encode($data['arrnames'] ?? '', true),
                    'status'  => $status,
                ];
            }
            // //判断推荐选址数
            // if ($data['ordertype'] == 1) {
            //     $tjaddress = (new Biaoji())->where(['del' => 1, 'orderid' => $data['orderid'], 'user_id ' => $this->request->user_id])->count();
            //     if ($tjaddress < 3) {
            //         $this->result([], 1, '推荐选址位置必须不低于3个');
            //     }
            // }
            //判断订单权限
            $xzrytype = 1;
            if ($data['ordertype'] == 1) {
                if (empty($data['hktype'])) {
                    $this->result([], 1, '请选择回款情况');
                }
                $order = (new Business())->where(['id' => $data['orderid']])->find();
                if ($order['duid'] != $this->request->user_id) {
                    $xzrytype = 2;
                }
            }
            if ($data['ordertype'] == 2) {
                $order = (new Business())->where(['id' => $data['orderid']])->find();
                if ($order['kuid'] != $this->request->user_id) {
                    $xzrytype = 2;
                }
            }
            if (empty($order) && $data['orderid'] > 0) {
                $this->result([], 1, '无订单权限，请刷新页面重试');
            }
            //查看是否已提交报销
            $havere = (new Reimburs())->where(['user_id' => $this->request->user_id, 'old' => 1, 'orderid' => $data['orderid'], 'type' => $data['ordertype'], 'status' => [1, 2]])->count();
            if ($havere >= 1 && $data['orderid'] > 0) {
                $this->result([], 1, '您已提交过此订单此类型的申报，如审核中信息错误可撤回后提交');
            }
            if (!empty($data['hktype']) && $data['hktype'] >= 3 && empty($data['hktext'])) {
                $this->result([], 1, '请填写回款原因');
            }
            $post = [
                'user_id' => $this->request->user_id,
                'orderid' => $data['orderid'],
                'type' => $data['ordertype'],
                'total' => 0,
                'status' => 1,
                'name' => $data['name'] ?? '',
                'address' => $data['address'] ?? '',
                'jobtype' => $data['jobtype'] ?? 0,
                'groups' => $data['groups'] ?? 0,
                'mianji' => $data['mianji'] ?? 0,
                'hktype' => $data['hktype'] ?? 0,
                'hktext' => $data['hktext'] ?? '',
            ];
            $postlog = [];
            foreach ($data['datas'] as $datas) {
                $datas['money'] = (float)$datas['money'] ?? 0;
                if (empty($datas['money'])) {
                    $this->result([], 1, '报销金额必须大于0');
                }
                if (!empty($data['version']) &&  $post['type'] != 100 && $post['type'] != 99 && (empty($datas['cfaddress']) || empty($datas['ddaddress']) || empty($datas['cfdates']) || empty($datas['dddates']) || empty($datas['kehuname']) || empty($datas['gztype_name']))) {
                    $this->result([], 1, '请填写出完整出发地、到达地、客户信息等');
                }
                if (empty($datas['dates']) &&  $post['type'] != 100) {
                    $this->result([], 1, '请填写费用发生日期');
                }
                if (empty($datas['type'])) {
                    $this->result([], 1, '请填写费用报销类型');
                }
                if (empty($datas['remark']) && empty($data['version'])) {
                    $this->result([], 1, '请填写费用明细说明');
                }
                if (empty($datas['remark']) && $post['type'] == 100) {
                    $this->result([], 1, '请填写费用说明');
                }
                $post['total'] += $datas['money'];
                if (!is_array($datas['pinzheng'])) {
                    $this->result([], 1, '凭证上传格式错误');
                }
                if (!is_array($datas['fujian'])) {
                    $this->result([], 1, '附件上传格式错误');
                }
                if (count($datas['pinzheng']) < 1 &&  $post['type'] != 100) {
                    $this->result([], 1, '每个报销明细必须上传至少一张图片');
                }
                foreach ($datas['pinzheng'] as $pinzheng) {
                    if (!empty($pinzheng['status']) && $pinzheng['status'] == 'uploading') {
                        $this->result([], 1, '图片正在上传,请等待');
                    }
                }
                foreach ($datas['fujian'] as $fujian) {
                    if (!empty($fujian['status']) && $fujian['status'] == 'uploading') {
                        $this->result([], 1, '图片正在上传,请等待');
                    }
                }
                $mingxis = [];
                $datas['mingxi'] = $datas['mingxi'] ?? [];
                foreach ($datas['mingxi'] as $mingxi) {
                    if ((!empty($mingxi['title']) && empty($mingxi['total'])) || (empty($mingxi['title']) && !empty($mingxi['total']))) {
                        $this->result([], 1, '内容或金额需均填写或均不填写');
                    }
                    if (!empty($mingxi['title']) && !empty($mingxi['total'])) {
                        $mblength = mb_strlen($mingxi['title'], 'UTF-8');
                        if ($mblength > 120) {
                            $this->result([], 1, '费用明细中报销内容长度不能超过120个字符');
                        }
                        $mingxis[] = $mingxi;
                    }
                }
                if (count($mingxis) < 1 && !empty($data['isnew']) &&  $post['type'] != 100) {
                    $this->result([], 1, '报销明细必须有一条');
                }
                $postlog[] = [
                    'orderid' => $data['orderid'],
                    'money' => $datas['money'],
                    'reimbursid' => 0,
                    'dates' => $datas['dates'],
                    'type' => $datas['type'],
                    'remark' => $datas['remark'],
                    'pinzheng' => json_encode($datas['pinzheng'] ?? '', true),
                    'fujian' => json_encode($datas['fujian'] ?? '', true),
                    'mingxi' => json_encode($mingxis ?? '', true) ?? '',
                    'cfaddress' => $datas['cfaddress'] ?? '',
                    'ddaddress' => $datas['ddaddress'] ?? '',
                    'cfdates' => $datas['cfdates'] ?? '',
                    'dddates' => $datas['dddates'] ?? '',
                    'kehuname' => $datas['kehuname'] ?? '',
                    'gztype' => $datas['gztype'] ?? '',
                    'gztype_name' => $datas['gztype_name'] ?? '',
                    'isnew' => $data['isnew'] ?? 1
                ];
            }
            if (count($postlog) < 1) {
                $this->result([], 1, '报销明细错误');
            }
            // if ($this->request->user_id == 108) {
            //     dump($postlog);
            //     die;
            // }
            //保存
            Db::startTrans();
            try {
                $reimbursid = (new Reimburs())->strict(false)->insertGetId($post);
                foreach ($postlog as &$log) {
                    $log['reimbursid'] = $reimbursid;
                }
                (new ReimbursLog())->allowfield(true)->saveAll($postlog);
                if (empty($uporder) && !empty($upsave)) {
                    (new Uploadtk())->allowfield(true)->save($upsave);
                } elseif (!empty($uporder) && !empty($upsave)) {
                    (new Uploadtk())->allowfield(true)->save($upsave, ['id' => $uporder['id']]);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, $e->getMessage());
            }
            $this->result([], 0, '操作成功');
        } else {
            $data = $this->request->get();
            $page = $data['page'] ?? 1;
            $limit =  $data['limit'] ?? 10;
            $page = (int)$page;
            $limit = (int)$limit;
            if (!empty($data['id'])) {
                $results = (new Reimburs())->where('id', $data['id'])->select();
            } else {
                $results = (new Reimburs())->limit($limit)->page($page)->order('id desc')->where('user_id', $this->request->user_id)->select();
            }
            foreach ($results as $result) {
                if ($result['orderid'] > 0) {
                    $business = (new Business())->where('id', $result['orderid'])->find() ?? '';
                    $result['name'] = $business['name'] ?? '';
                    $result['groups'] = $business['type'] ?? '';
                    $result['jobtype'] = $business['ordertype'] ?? 0;
                }
                $logs = (new ReimbursLog())->where('reimbursid', $result['id'])->select();
                foreach ($logs as $log) {
                    $mingxi = json_decode($log['mingxi'] ?? '', true) ?? [];
                    $mingxi[] = [
                        'title' =>  '',
                        'total' => '',
                    ];
                    $log['mingxi'] = $mingxi;
                    $log['pinzheng'] = json_decode($log['pinzheng'] ?? '', true) ?? [];
                    $log['fujian'] = json_decode($log['fujian'] ?? '', true) ?? [];
                    $log['typename'] = config()["config"]['reimburs_type'][$log['type']] ?? '';
                }
                $result['log'] = $logs;
                $result['status_text'] = config()["config"]['reimburs_status'][$result['status']] ?? '';
                $result['groupname'] = config()["config"]['type'][$result['groups']] ?? '';
                $result['jobtypename'] = config()["config"]['ordertype'][$result['jobtype']] ?? '';
            }
            $this->result($results, 0, '操作成功');
        }
    }

    //开业信息提交
    public function addkaiye()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'id' => 'require',
            'reAddress' => 'require',
            'address' => 'require',
            'lat' => 'require',
            'lon' => 'require',
            'shanghuo' => 'require|in:1,2',
            'huozhuang' => 'require|in:1,2',
            'images' => 'require',
            'images1' => 'require',
            'video' => 'require',
        ], [
            'id.require' => 'ID不能为空',
            'reAddress.require' => '定位地址不能为空',
            'lat.require' => '坐标地址错误，请重新定位',
            'lon.require' => '坐标地址错误，请重新定位',
            'address.require' => '详细地址不能为空',
            'shanghuo.require' => '上货状态请填写',
            'shanghuo.in' => '上货状态不正确',
            'huozhuang.require' => '货架安装状态请填写',
            'huozhuang.in' => '货架安装不正确',
            'images.require' => '回执单必须上传',
            'images1.require' => '现场照片必须上传',
            'video.require' => '现场视频必须上传',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $order = (new Business())->where(['id' => $data['id'], 'old' => [2, 3], 'kuid' => $this->request->user_id])->find();
        if (empty($order)) {
            $this->result([], 1, '任务不存在或无权限');
        }
        if ($order['schedule'] != 5  && $order['schedule'] != 6) {
            $this->result([], 1, '当前任务进度不可提交信息');
        }
        if (count($data['images']) < 2) {
            $this->result([], 1, '请上传至少俩张清晰回执单');
        }
        if (count($data['images1']) < 3) {
            $this->result([], 1, '请上传至少3张现场照片');
        }
        if (count($data['video']) < 3) {
            $this->result([], 1, '请上传至少3个现场视频');
        }
        if (!empty($data['version']) && $order['schedule'] == 5) {
            if (empty($data['video5']) && empty($data['video6'])) {
                $this->result([], 1, '工作途中和开业人气视频必须上传');
            }
            if (count($data['video5']) <= 0 || count($data['video6']) <= 0) {
                $this->result([], 1, '工作途中和开业人气视频必须上传各一张');
            }
        }
        $post = [
            'getaddress' => $data['reAddress'],
            'address' => $data['address'],
            'lat' => $data['lat'],
            'lon' => $data['lon'],
            'shanghuo' => $data['shanghuo'],
            'huozhuang' => $data['huozhuang'],
            'images2' => json_encode($data['images'] ?? [], true),
            'images3' => json_encode($data['images1'] ?? [], true),
            'images5' => json_encode($data['images5'] ?? [], true),
            'sginfo' => json_encode($data['sginfo'] ?? [], true),
            'video' => json_encode($data['video'] ?? [], true),
            'video5' => json_encode($data['video5'] ?? [], true),
            'video6' => json_encode($data['video6'] ?? [], true),
            'kremark' => $data['remark'] ?? '',
            'times' => $data['times'] ?? '',
            'mobile' => $data['bianma'] ?? '',
            'kyupdated' => date('Y-m-d H:i:s')
        ];
        if (!empty($data['weikuan'])) {
            $post['weikuan'] = $data['weikuan'];
            //全部尾款
            if ($post['weikuan'] == 3 && $post['weikuan'] != $order['weikuan']) {
                $post['weikuanback'] = $order['weikuan'];
                $post['weikuanstatus'] = 2;
            } elseif ($post['weikuan'] != 3) {
                $post['weikuanback'] = 0;
                $post['weikuanstatus'] = 1;
            }
        }
        $url = 'https://apis.map.qq.com/ws/geocoder/v1';
        try {
            $result = api_curl($url, ['location' => $data['lat'] . ',' . $data['lon'], 'key' => 'KHMBZ-ADFKZ-H2IXE-TUFHJ-RR4LV-N7F4D', 'poi_options' => 'radius=50;policy=5']);
            $post['province'] = $result['result']['ad_info']['province'] ?? '';
            $post['city'] = $result['result']['ad_info']['city'] ?? '';
            $post['area'] = $result['result']['ad_info']['district'] ?? '';
        } catch (\Exception $e) {
            $this->result([], 1, $e->getMessage());
        }
        $message = [];
        if ($order['schedule'] == 5) {
            //通知管理员
            $guanli = (new Users())->where(['type' => 5, 'del' => 1])->select();
            foreach ($guanli as $guanlis) {
                $message[] = [
                    'orderid' => $order['id'],
                    'user_id' =>  $guanlis['id'],
                    'ouser_id' => 0,
                    'status' => $order['schedule'],
                    'endstatus' => 6,
                    'text' => '开业人员已提交信息，请查看信息并确认是否开业',
                ];
            }
            $post['schedule'] = 6;
        }
        $model = new Business();
        $res = $model->allowfield(true)->save($post, ['id' => $data['id']]);
        if ($res) {
            if (count($message) > 0) {
                (new Messages())->allowfield(true)->saveAll($message);
            }
            $this->result([], 0, '提交成功');
        }
        $this->result([], 1, '提交失败，请重试');
    }

    //售后信息提交
    public function addshouhou()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'id' => 'require',
            'zhuangxiu' => 'require|in:1,2,3',
            'ishuo' => 'require|in:1,2',
            'isfirst' => 'require|in:1,2',
            'images' => 'require',
        ], [
            'id.require' => 'ID不能为空',
            'zhuangxiu.require' => '装修状态请填写',
            'zhuangxiu.in' => '装修状态不正确',
            'isfirst.require' => '首单发货状态状态请填写',
            'isfirst.in' => '首单发货状态不正确',
            'ishuo.require' => '货架发货状态请填写',
            'ishuo.in' => '货架发货不正确',
            'images.require' => '图纸必须上传',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $order = (new Business())->where(['id' => $data['id'], 'suid' => $this->request->user_id])->find();
        if (empty($order)) {
            $this->result([], 1, '任务不存在或无权限');
        }
        if ($order['schedule'] != 3  && $order['schedule'] != 4 && $order['schedule'] != 5) {
            $this->result([], 1, '当前任务进度不可更改售后信息');
        }
        if (count($data['images']) < 1) {
            $this->result([], 1, '请上传至少一张图纸');
        }
        $post = [
            'zhuangxiu' => $data['zhuangxiu'],
            'isfirst' => $data['isfirst'],
            'ishuo' => $data['ishuo'],
            'images1' => json_encode($data['images'] ?? [], true),
            'images5' => json_encode($data['images5'] ?? [], true),
            'sremark' => $data['remark'] ?? ''
        ];
        if (!empty($data['weikuan'])) {
            $post['weikuan'] = $data['weikuan'];
        }
        if ($data['isfirst'] == 2 && !empty($data['firsttimes'])) {
            $post['firsttimes'] = $data['firsttimes'];
        }
        if ($data['isfirst'] == 2 && empty($data['firsttimes'])) {
            $this->result([], 1, '首单发货日期必须填写');
        }
        $message = [];
        if ($order['schedule'] == 3) {
            //通知管理员
            $post['schedule'] = 4;
            $guanli = (new Users())->where(['type' => 5, 'del' => 1])->select();
            foreach ($guanli as $guanlis) {
                $message[] = [
                    'orderid' => $order['id'],
                    'user_id' =>  $guanlis['id'],
                    'ouser_id' => 0,
                    'status' => $order['schedule'],
                    'endstatus' => $post['schedule'],
                    'text' => '有新的待指派开业人员，请注意跟进',
                ];
            }
        } else {
            $guanli = (new Users())->where(['type' => 5, 'del' => 1])->select();
            foreach ($guanli as $guanlis) {
                $message[] = [
                    'orderid' => $order['id'],
                    'user_id' =>  $guanlis['id'],
                    'ouser_id' => 0,
                    'status' => $order['schedule'],
                    'endstatus' => $order['schedule'],
                    'text' => '售后人员修改任务单信息，请留意',
                ];
            }
        }
        $model = new Business();
        $res = $model->allowfield(true)->save($post, ['id' => $data['id']]);
        if ($res) {
            if (count($message) > 0) {
                (new Messages())->allowfield(true)->saveAll($message);
            }
            $this->result([], 0, '提交成功');
        }
        $this->result([], 1, '提交失败，请重试');
    }

    //选址信息提交
    public function addmarks()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
                'title' => 'require',
                'reAddress' => 'require',
                'address' => 'require',
                'lat' => 'require|gt:0',
                'lon' => 'require|gt:0',
                'yxmm' =>  'require',
                'mtcd' =>  'require',
                'zrf' =>  'require',
                'dmzj' =>  'require',
                'dpmj' =>  'require',
                'htsj' => 'require',
                'zffs' =>  'require',
                'texts' =>  'require',
            ], [
                'id.require' => 'ID不能为空',
                'title.require' => '个人备注不能为空',
                'reAddress.require' => '定位地址不能为空',
                'lat.gt' => '定位坐标错误',
                'lon.gt' => '定位坐标错误',
                'lat.require' => '坐标地址错误，请重新定位',
                'lon.require' => '坐标地址错误，请重新定位',
                'address.require' => '详细地址不能为空',
                'yxmm.require' =>  '意向门面内容不能为空',
                'mtcd.require' =>  '门头长度不能为空',
                'zrf.require' =>  '转让费不能为空',
                'dmzj.require' =>  '店面租金不能为空',
                'dpmj.require' =>  '店铺面积不能为空',
                'htsj.require' => '合同时间不能为空',
                'zffs.require' =>  '支付方式不能为空',
                'texts.require' =>  '备注信息不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            if (count($data['fileList1']) < 1) {
                $this->result([], 1, '请上传至少一张门头照片');
            }
            if (count($data['fileList2']) < 1) {
                $this->result([], 1, '请上传至少一个店内解析视频');
            }
            if (count($data['fileList10']) < 1) {
                $this->result([], 1, '请上传至少一张店内拍照图片');
            }
            $post = [
                'title' => $data['title'] ?? '',
                'reAddress' => $data['reAddress'] ?? '',
                'address' => $data['address'] ?? '',
                'lat' => $data['lat'] ?? 0,
                'lon' => $data['lon'] ?? 0,
                'yxmm' => $data['yxmm'] ?? '',
                'mtcd' => $data['mtcd'] ?? '',
                'zrf' => $data['zrf'] ?? '',
                'dmzj' => $data['dmzj'] ?? '',
                'dpmj' => $data['dpmj'] ?? '',
                'htsj' => $data['htsj'] ?? '',
                'zffs' => $data['zffs'] ?? '',
                'texts' => $data['texts'] ?? '',
                'status' => 1,
                'fileList1' => json_encode($data['fileList1'] ?? [], true), //现场照片
                'fileList2' => json_encode($data['fileList2'] ?? [], true), //现场视频
                'fileList10' => json_encode($data['fileList10'] ?? [], true), //回执单
            ];
            $model = new Marks();
            if (empty($data['id'])) {
                $post['user_id'] =  $this->request->user_id;
                $res = $model->allowfield(true)->save($post);
            } else {
                $order = $model->where(['user_id' => $this->request->user_id, 'id' => $data['id']])->find();
                if (empty(($order))) {
                    $this->result([], 1, '数据不存在或无权限');
                }
                if ($order['status'] == 2) {
                    $this->result([], 1, '数据已处于不可编辑状态');
                }
                $res = $model->allowfield(true)->save($post, ['id' => $data['id']]);
            }
            if ($res) {
                $this->result([], 0, '提交成功');
            }
            $this->result([], 1, '提交失败，请重试');
        } else {
            $id = $this->request->get('id/d', 0);
            $shop = (new Marks())->where('id', $id)->find();
            if ($shop) {
                $shop['fileList1'] = json_decode($shop['fileList1'] ?? '', true) ?? [];
                $shop['fileList2'] = json_decode($shop['fileList2'] ?? '', true) ?? [];
                $shop['fileList10'] = json_decode($shop['fileList10'] ?? '', true) ?? [];
            }
            $this->result($shop, 0, '获取成功');
        }
    }

    //选址信息提交
    public function addxuanzhi()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'id' => 'require',
            'name' => 'require',
            'mobile' => 'require',
            'reAddress' => 'require',
            'address' => 'require',
            'lat' => 'require',
            'lon' => 'require',
            'weikuan' => 'require|in:1,2,3',
            'images' => 'require',
        ], [
            'id.require' => 'ID不能为空',
            'name.require' => '客户名称不能为空',
            'mobile.require' => '客户电话不能为空',
            'reAddress.require' => '定位地址不能为空',
            'lat.require' => '坐标地址错误，请重新定位',
            'lon.require' => '坐标地址错误，请重新定位',
            'address.require' => '详细地址不能为空',
            'weikuan.require' => '尾款状态请填写',
            'weikuan.in' => '尾款状态不正确',
            'images.require' => '图纸必须上传',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        if (empty($data['mobile'])) {
            $this->result([], 1, '请填写客户手机号');
        }
        if (!preg_match("/^1[0-9]{10}$/", $data['mobile'])) {
            $this->result([], 1, '手机格式不正确,请检查手机号是否正确或含有空格');
        }
        $order = (new Business())->where(['id' => $data['id'], 'duid' => $this->request->user_id])->find();
        if (empty($order)) {
            $this->result([], 1, '派单任务不存在或无权限');
        }
        if ($order['schedule'] != 2  && $order['schedule'] != 3) {
            $this->result([], 1, '当前任务进度不可更改选址信息');
        }
        if (count($data['images']) < 1) {
            $this->result([], 1, '请上传至少一张图纸');
        }
        if (count($data['images9']) < 1) {
            $this->result([], 1, '请上传至少一张回执单图片');
        }
        if (count($data['images7']) < 1) {
            $this->result([], 1, '请上传至少一张业务经理修改、添加合同内容图片');
        }
        // if ($order['schedule'] == 2 && count($data['images11']) < 1) {
        //     $this->result([], 1, '房产证明照片必须上传1张');
        // }
        $post = [
            'name' => $data['name'],
            'phone' => $data['mobile'],
            'getaddress' => $data['reAddress'],
            'address' => $data['address'],
            'lat' => $data['lat'],
            'lon' => $data['lon'],
            'weikuan' => $data['weikuan'],
            'images' => json_encode($data['images'] ?? [], true),
            'images4' => json_encode($data['images4'] ?? [], true),
            'images5' => json_encode($data['images5'] ?? [], true),
            'images6' => json_encode($data['images6'] ?? [], true),
            'images7' => json_encode($data['images7'] ?? [], true),
            'images9' => json_encode($data['images9'] ?? [], true),
            'images10' => json_encode($data['images10'] ?? [], true),
            'images11' => json_encode($data['images11'] ?? [], true),
            'video1' => json_encode($data['video1'] ?? [], true),
            'hetongtype' => $data['hetongtype'] ?? 0,
            'hetongtext' => $data['hetongtext'] ?? "",
            'dremark' => $data['remark'] ?? '',
            'htqdr' => $data['htqdr'] ?? '',
            'storetype' => $data['storetype'] ?? 0,
            'mianji' => $data['mianji'] ?? 0,
            'canyyzz' => $data['canyyzz'] ?? 0,
        ];
        if (!empty($data['name2'])) {
            $post['name2'] = $data['name2'];
        }
        if (!empty($data['mobile2'])) {
            $post['phone2'] = $data['mobile2'];
        }
        // $post['backdata'] =  json_encode(array_merge($order->toArray(), $post) ?? [], true);
        if ($post['hetongtype'] == 3 && empty($post['hetongtext'])) {
            $this->result([], 1, '待签合同原因必须填写');
        }
        if ($post['hetongtype'] <= 2 && empty($post['htqdr'])) {
            $this->result([], 1, '合同类型和签订人必须填写');
        }
        $url = 'https://apis.map.qq.com/ws/geocoder/v1';
        try {
            $result = api_curl($url, ['location' => $data['lat'] . ',' . $data['lon'], 'key' => 'KHMBZ-ADFKZ-H2IXE-TUFHJ-RR4LV-N7F4D', 'poi_options' => 'radius=50;policy=5']);
            $post['province'] = $result['result']['ad_info']['province'] ?? '';
            $post['city'] = $result['result']['ad_info']['city'] ?? '';
            $post['area'] = $result['result']['ad_info']['district'] ?? '';
        } catch (\Exception $e) {
            $this->result([], 1, $e->getMessage());
        }
        $message = [];
        if ($order['schedule'] == 2) {
            $post['schedule'] = 3;
            $post['status'] = 2;
            $post['isshenhe'] = 1;
            $message[] = [
                'orderid' => $order['id'],
                'user_id' =>  $order['suid'],
                'ouser_id' => 0,
                'status' => $order['schedule'],
                'endstatus' => $post['schedule'],
                'text' => '您的售后单选址完成，请填写信息',
            ];
        }
        $model = new Business();
        //************************** */
        //附近选址
        $filed = 'ROUND(6378.138*2*ASIN(SQRT(POW(SIN((' . $data['lat'] . '*PI()/180-lat*PI()/180)/2),2)+COS(' . $data['lat'] . '*PI()/180)*COS(lat*PI()/180)*POW(SIN((' . $data['lon'] . '*PI()/180-lon*PI()/180)/2),2)))*100)/100 AS dist';
        // $havemendian = (new Business())
        //     ->field('id,name,' . $filed)
        //     ->where('id', '<>', $data['id'])
        //     ->where('type', $order['type'])
        //     ->order('dist asc')->having('dist <= 0.35')->where(['status' => [1, 2, 3]])->find();
        // $restext = '提交成功';
        // if (!empty($havemendian)) {
        $post['schedule'] = $order['schedule'];
        $post['status'] = $order['status'];
        $post['isshenhe'] = 2;
        $message = [];
        $restext = "资料上传成功，请等待审核";
        $guanli = (new Users())->where(['type' => 4, 'del' => 1])->select();
        foreach ($guanli as $guanlis) {
            $message[] = [
                'orderid' => $data['id'],
                'user_id' =>  $guanlis['id'],
                'ouser_id' => 0,
                'status' => 1,
                'endstatus' => 1,
                'text' => '督导提交地址,请进行审核',
            ];
        }
        // }
        //附近门店判断结束
        //************************** */
        $res = $model->allowfield(true)->save($post, ['id' => $data['id']]);
        if ($res) {
            if (count($message) > 0) {
                (new Messages())->allowfield(true)->saveAll($message);
            }
            $this->result([], 0, $restext);
        }
        $this->result([], 1, '提交失败，请重试');
    }

    //选址信息提交2.0
    public function addxuanzhi_new()
    {
        $data = $this->request->post();
        if (empty($data['subtype'])) {
            $this->result([], 1, '提交类型为空');
        }
        switch ($data['subtype']) {
            case '1':
                $validate = new Validate([
                    'id' => 'require',
                    'reAddress' => 'require',
                    'address' => 'require',
                    'lat' => 'require',
                    'lon' => 'require',
                ], [
                    'id.require' => 'ID不能为空',
                    'reAddress.require' => '定位地址不能为空',
                    'lat.require' => '坐标地址错误，请重新定位',
                    'lon.require' => '坐标地址错误，请重新定位',
                    'address.require' => '详细地址不能为空',
                ]);
                if (!$validate->check($data)) {
                    $this->result([], 1, $validate->getError());
                }
                if (!empty($data['mobile']) && !preg_match("/^1[0-9]{10}$/", $data['mobile'])) {
                    $this->result([], 1, '手机号不正确,请检查手机号是否正确或含有空格');
                }
                if (!empty($data['mobile2']) && !preg_match("/^1[0-9]{10}$/", $data['mobile2'])) {
                    $this->result([], 1, '手机号码2不正确,请检查手机号是否正确或含有空格');
                }
                $order = (new Business())->where(['id' => $data['id']])->find();
                if (empty($order)) {
                    $this->result([], 1, '派单任务不存在');
                }
                // $xxhave = (new Businessxq())->where(['orderid' => $data['id'], 'type' => 1, 'user_id' => $this->request->user_id])->find();
                // if ($order['duid'] != $this->request->user_id && empty($xxhave)) {
                //     $this->result([], 1, '无操作权限');
                // }
                if ($this->request->user['type'] != 2) {
                    $this->result([], 1, '无操作权限');
                }
                if ($order['isshenhe'] == 2) {
                    $this->result([], 1, '选址信息审核中，无法提交，请核实附近同品牌门店');
                }
                if ($order['schedule'] != 1 && $order['schedule'] != 2  && $order['schedule'] != 3) {
                    $this->result([], 1, '当前任务进度不可更改选址信息');
                }
                if (!empty($data['version']) && $order['foundation'] == 1 && (empty($data['video4']) || count($data['video4']) <= 0)) {
                    //$this->result([], 1, '选址途中视频必须上传');
                }
                $post = [
                    'name' => $data['name'],
                    'phone' => $data['mobile'] ?? '',
                    'name2' => $data['name2'] ?? '',
                    'phone2' => $data['mobile2'] ?? '',
                    'getaddress' => $data['reAddress'] ?? '',
                    'address' => $data['address'] ?? '',
                    'lat' => $data['lat'] ?? '',
                    'lon' => $data['lon'] ?? '',
                    'bdmark' => $data['bdmark'] ?? 0,
                    'images' => json_encode($data['images'] ?? [], true),
                    'images4' => json_encode($data['images4'] ?? [], true),
                    'images10' => json_encode($data['images10'] ?? [], true),
                    'video1' => json_encode($data['video1'] ?? [], true),
                    'video4' => json_encode($data['video4'] ?? [], true),
                    'hetongtext' => $data['hetongtext'] ?? "",
                    'storetype' => $data['storetype'] ?? 0,
                    'mianji' => $data['mianji'] ?? 0,
                    'foundation' => 2,
                    'jcmessagetime' => date('Y-m-d H:i:s'),
                    'jcupdated' => date('Y-m-d H:i:s')
                ];
                $url = 'https://apis.map.qq.com/ws/geocoder/v1';
                try {
                    $result = api_curl($url, ['location' => $data['lat'] . ',' . $data['lon'], 'key' => 'KHMBZ-ADFKZ-H2IXE-TUFHJ-RR4LV-N7F4D', 'poi_options' => 'radius=50;policy=5']);
                    $post['province'] = $result['result']['ad_info']['province'] ?? '';
                    $post['city'] = $result['result']['ad_info']['city'] ?? '';
                    $post['area'] = $result['result']['ad_info']['district'] ?? '';
                } catch (\Exception $e) {
                    $this->result([], 1, $e->getMessage());
                }
                $message = [];
                $model = new Business();
                //************************** */
                //附近选址
                $filed = 'ROUND(6378.138*2*ASIN(SQRT(POW(SIN((' . $data['lat'] . '*PI()/180-lat*PI()/180)/2),2)+COS(' . $data['lat'] . '*PI()/180)*COS(lat*PI()/180)*POW(SIN((' . $data['lon'] . '*PI()/180-lon*PI()/180)/2),2)))*100)/100 AS dist';
                $havemendian = (new Business())
                    ->field('id,name,' . $filed)
                    ->where('id', '<>', $data['id'])
                    ->where('type', $order['type'])
                    ->order('dist asc')->having('dist <= 0.35')->where(['status' => [1, 2, 3]])->find();
                //更新订单状态
                if ($order['schedule'] == 1) {
                    $post['schedule'] = 2;
                }
                if ($order['schedule'] == 2 && ($order['contract'] == 2 || $order['ordertype'] == 3) && empty($havemendian)) {
                    $post['schedule'] = 3;
                    $post['status'] = 2;
                    $message[] = [
                        'orderid' => $order['id'],
                        'user_id' =>  $order['suid'],
                        'ouser_id' => 0,
                        'status' => $order['schedule'],
                        'endstatus' => $post['schedule'],
                        'text' => '您的售后单选址完成，请填写信息'
                    ];
                }
                $restext = '提交成功';
                if (!empty($havemendian)) {
                    $post['schedule'] = $order['schedule'];
                    $post['status'] = $order['status'];
                    $post['isshenhe'] = 2;
                    $message = [];
                    $restext = "资料上传成功，由于该地址附近300m内存在门店，当前订单地址进入审核状态";
                    $guanli = (new Users())->where(['type' => 4, 'del' => 1, 'look' => 1])->select();
                    foreach ($guanli as $guanlis) {
                        $message[] = [
                            'orderid' => $data['id'],
                            'user_id' =>  $guanlis['id'],
                            'ouser_id' => 0,
                            'status' => 1,
                            'endstatus' => 1,
                            'text' => '督导提交地址附近300m存在客户(' . $havemendian['name'] . ')，请进行审核'
                        ];
                    }
                }
                // $ishavesc = (new Sucai())->where(['isdefault' => 0, 'orderid' => $order['id'], 'type' => 1])->find();
                // $xuan = [
                //     'isdefault' => 0,
                //     'user_id' => 0,
                //     'orderid' => $order['id'],
                //     'type' => 1,
                //     'pinpai' => $order['type'],
                //     'images4' => json_encode($data['images4'] ?? [], true),
                //     'images10' => json_encode($data['images10'] ?? [], true),
                //     'video1' => json_encode($data['video1'] ?? [], true),
                //     'sctype' => 3,
                //     'status' => 2,
                //     'finished' => date('Y-m-d H:i:s')
                // ];
                //附近门店判断结束
                //************************** */
                $res = $model->allowfield(true)->save($post, ['id' => $data['id']]);
                if ($res) {
                    // if (empty($ishavesc)) {
                    //     (new Sucai())->allowfield(true)->save($xuan);
                    // } else {
                    //     (new Sucai())->allowfield(true)->save($xuan, ['id' => $ishavesc['id']]);
                    // }
                    if (count($message) > 0) {
                        (new Messages())->allowfield(true)->saveAll($message);
                    }
                    $this->result([], 0, $restext);
                }
                $this->result([], 1, '提交失败，请重试');
                break;
            case '2':
                $validate = new Validate([
                    'id' => 'require',
                    'images11' => 'require',
                    'images7' => 'require',
                    'images9' => 'require',
                ], [
                    'id.require' => 'ID不能为空',
                    'images11.require' => '房产证明图片不能为空',
                    'images7.require' => '业务经理修改、添加合同内容图片不能为空',
                    'images9.require' => '回执单图片不能为空',
                ]);
                if (!$validate->check($data)) {
                    $this->result([], 1, $validate->getError());
                }
                $order = (new Business())->where(['id' => $data['id']])->find();
                if (empty($order)) {
                    $this->result([], 1, '派单任务不存在');
                }
                $xxhave = (new Businessxq())->where(['orderid' => $data['id'], 'type' => 1, 'user_id' => $this->request->user_id])->find();
                if ($order['duid'] != $this->request->user_id && empty($xxhave)) {
                    $this->result([], 1, '无操作权限');
                }
                if ($order['schedule'] != 2  && $order['schedule'] != 3 && $order['weikuan'] >= 3) {
                    $this->result([], 1, '当前任务进度不可更改选址信息');
                }
                if (count($data['images9']) < 1) {
                    $this->result([], 1, '请上传至少一张回执单图片');
                }
                if (count($data['images7']) < 1) {
                    $this->result([], 1, '请上传至少一张业务经理修改、添加合同内容图片');
                }
                if (!empty($data['version']) && $order['contract'] == 1) {
                    if (empty($data['video3']) && empty($data['images12'])) {
                        $this->result([], 1, '手拉旗照片或合同视频必须上传一样');
                    }
                    if (count($data['video3']) <= 0 && count($data['images12']) <= 0) {
                        $this->result([], 1, '手拉旗照片或合同视频必须上传一样');
                    }
                }
                $post = [
                    'weikuan' => $data['weikuan'] ?? 0,
                    'images5' => json_encode($data['images5'] ?? [], true),
                    'images6' => json_encode($data['images6'] ?? [], true),
                    'images7' => json_encode($data['images7'] ?? [], true),
                    'images9' => json_encode($data['images9'] ?? [], true),
                    'images11' => json_encode($data['images11'] ?? [], true),
                    'images12' => json_encode($data['images12'] ?? [], true),
                    'video3' => json_encode($data['video3'] ?? [], true),
                    'hetongtype' => $data['hetongtype'] ?? 0,
                    'hetongtext' => $data['hetongtext'] ?? "",
                    'dremark' => $data['remark'] ?? '',
                    'htqdr' => $data['htqdr'] ?? '',
                    'canyyzz' => $data['canyyzz'] ?? 0,
                    'contract' => 2,
                    'htupdated' => date('Y-m-d H:i:s')
                ];
                //全部尾款
                if ($post['weikuan'] == 3 && $post['weikuan'] != $order['weikuan']) {
                    $post['weikuanback'] = $order['weikuan'];
                    $post['weikuanstatus'] = 2;
                } elseif ($post['weikuan'] != 3) {
                    $post['weikuanback'] = 0;
                    $post['weikuanstatus'] = 1;
                }
                if ($post['hetongtype'] == 3 && empty($post['hetongtext'])) {
                    $this->result([], 1, '待签合同原因必须填写');
                }
                if ($post['hetongtype'] < 3 && empty($post['htqdr'])) {
                    $this->result([], 1, '合同签订人必须填写');
                }
                if ($post['weikuan']  > 1 && count($data['images5']) < 1) {
                    $this->result([], 1, '回款凭证必须上传');
                }
                //更新订单状态
                $message = [];
                $model = new Business();
                if ($order['schedule'] == 2 && $order['foundation'] == 2 && $order['isshenhe'] == 1) {
                    $post['schedule'] = 3;
                    $post['status'] = 2;
                    $message[] = [
                        'orderid' => $order['id'],
                        'user_id' =>  $order['suid'],
                        'ouser_id' => 0,
                        'status' => $order['schedule'],
                        'endstatus' => $post['schedule'],
                        'text' => '您的售后单选址完成，请填写信息',
                    ];
                }
                $res = $model->allowfield(true)->save($post, ['id' => $data['id']]);
                $restext = "提交成功";
                if ($order['isshenhe'] != 1) {
                    $restext = "当前由于地址审核中或审核不通过,需要等待审核通过或重新提交地址任务状态才会变更";
                }
                if ($res) {
                    if (count($message) > 0) {
                        (new Messages())->allowfield(true)->saveAll($message);
                    }
                    $this->result([], 0, $restext);
                }
                $this->result([], 1, '提交失败，请重试');
                break;
            default:
                $this->result([], 1, '提交类型错误');
                break;
        }
    }

    //管理员指派选址督导或开业督导
    public function superStatus()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'status' => 'require',
        ], [
            'id.require' => 'ID不能为空',
            'status.require' => '状态不能为空',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $order = (new Business())->where(['id' => $data['id']])->find();
        if (empty($order)) {
            $this->result([], 1, '派单任务不存在');
        }
        $post = [];
        $message = [];
        $userstatus = [];
        switch ($data['status']) {
            case '2':
                if ($this->request->user['type'] != 4) {
                    $this->result([], 1, '无权操作此项');
                }
                if (empty($data['uid'])) {
                    $this->result([], 1, '督导账号不存在，请选择');
                }
                if ($order['schedule'] != 1  && $order['schedule'] != 2) {
                    $this->result([], 1, '当前任务进度不处于可指派状态');
                }
                if ($data['uid'] == -1) {
                    $data['uid'] = 0;
                    if ($order['schedule'] != 1) {
                        $post['schedule'] = 1;
                    }
                } else {
                    $dudao = (new Users())->where(['id' => $data['uid'], 'del' => 1])->find();
                    if (empty($dudao)) {
                        $this->result([], 1, '督导账号不存在，请重新选择');
                    }
                }
                $post['duid'] = $data['uid'];
                $post['baoxiaosons'] = $data['baoxiaosons'] ?? 1;
                if (!empty($data['ordertype'])) {
                    $post['ordertype'] = $data['ordertype'];
                } else {
                    if (empty($order['ordertype'])) {
                        $this->result([], 1, '请先编辑派单类型');
                    }
                }
                if ($order['schedule'] == 1) {
                    $post['schedule'] = 2;
                    $post['xcreated'] = date('Y-m-d H:i:s');
                    $message[] = [
                        'orderid' => $order['id'],
                        'user_id' =>  $post['duid'],
                        'ouser_id' => 0,
                        'status' => $order['schedule'],
                        'endstatus' => 2,
                        'text' => '您有新的选址任务单，请注意跟进',
                    ];
                    if ($post['duid'] > 0) {
                        $userstatus[] = [
                            'type' => 2,
                            'user_id' => $post['duid'],
                            'status' => 2,
                            'orderid' =>  $order['id'],
                        ];
                    }
                } else if ($post['duid'] != $order['duid']) {
                    $post['xcreated'] = date('Y-m-d H:i:s');
                    $message[] = [
                        'orderid' => $order['id'],
                        'user_id' =>  $post['duid'],
                        'ouser_id' => $order['duid'],
                        'status' => $order['schedule'],
                        'endstatus' => $order['schedule'],
                        'text' => '您有新的选址任务单，请注意跟进',
                    ];
                    $message[] = [
                        'orderid' => $order['id'],
                        'user_id' =>  $order['duid'],
                        'ouser_id' => 0,
                        'status' => $order['schedule'],
                        'endstatus' => $order['schedule'],
                        'text' => '您的选址任务单被取消，请留意',
                    ];
                    if ($post['duid'] > 0) {
                        $userstatus[] = [
                            'type' => 2,
                            'user_id' => $post['duid'],
                            'status' => 2,
                            'orderid' =>  $order['id'],
                        ];
                    }
                    if ($order['duid'] > 0) {
                        $userstatus[] = [
                            'type' => 1,
                            'user_id' => $order['duid'],
                            'status' => 2,
                            'orderid' =>  $order['id'],
                        ];
                    }
                }
                if (empty($order['backdata'])) {
                    $post['backdata'] =  json_encode(array_merge($order->toArray(), $post) ?? [], true);
                }
                break;
            case '5':
                if ($this->request->user['type'] != 5) {
                    $this->result([], 1, '无权操作此项');
                }
                if (empty($data['uid'])) {
                    $this->result([], 1, '督导账号不存在，请选择');
                }
                if ($order['schedule'] != 4   && $order['schedule'] != 5) {
                    $this->result([], 1, '当前任务进度不处于可指派状态');
                }
                if (empty($data['datemies'])) {
                    $this->result([], 1, '出发时间不能为空');
                }
                $dudao = (new Users())->where(['id' => $data['uid'], 'del' => 1])->find();
                if (empty($dudao)) {
                    $this->result([], 1, '督导账号不存在，请重新选择');
                }
                $post['kuid'] = $data['uid'];
                $post['kdates'] = $data['datemies'];
                $post['givermeark'] = $data['remark'] ?? '';
                if ($order['schedule'] == 4) {
                    $post['ycreated'] = date('Y-m-d H:i:s');
                    $post['schedule'] = 5;
                    //通知选址督导
                    $message[] = [
                        'orderid' => $data['id'],
                        'user_id' =>  $data['uid'],
                        'ouser_id' => 0,
                        'status' => $order['schedule'],
                        'endstatus' => $post['schedule'],
                        'text' => '您有新的开业任务单，请前往查看',
                    ];
                    if ($data['uid'] > 0) {
                        $userstatus[] = [
                            'type' => 2,
                            'user_id' => $data['uid'],
                            'status' => 2,
                            'orderid' =>  $order['id'],
                        ];
                    }
                } elseif ($order['duid'] > 0 && $order['duid'] != $data['uid']) {
                    $post['ycreated'] = date('Y-m-d H:i:s');
                    //通知选址督导
                    $message[] = [
                        'orderid' => $data['id'],
                        'user_id' =>  $data['uid'],
                        'ouser_id' => $order['kuid'],
                        'status' => $order['schedule'],
                        'endstatus' => $order['schedule'],
                        'text' => '您有新的开业任务单，请前往查看',
                    ];
                    //通知原开业督导
                    $message[] = [
                        'orderid' => $data['id'],
                        'user_id' =>  $order['kuid'],
                        'ouser_id' => 0,
                        'status' => $order['schedule'],
                        'endstatus' => $order['schedule'],
                        'text' => '已取消您此任务的身份，请留意',
                    ];
                    if ($data['uid'] > 0) {
                        $userstatus[] = [
                            'type' => 2,
                            'user_id' => $data['uid'],
                            'status' => 2,
                            'orderid' =>  $order['id'],
                        ];
                    }
                    if ($order['kuid'] > 0) {
                        $userstatus[] = [
                            'type' => 1,
                            'user_id' => $order['kuid'],
                            'status' => 2,
                            'orderid' =>  $order['id'],
                        ];
                    }
                }
                break;
            case '7':
                if ($this->request->user['type'] != 5) {
                    $this->result([], 1, '无权操作此项');
                }
                if ($order['schedule'] != 6) {
                    $this->result([], 1, '当前任务进度不处于可完结状态');
                }
                //通知所有人员
                $message[] = [
                    'orderid' => $data['id'],
                    'user_id' =>  $order['yuid'],
                    'ouser_id' => 0,
                    'status' => $order['schedule'],
                    'endstatus' => 5,
                    'text' => '此任务单已开业',
                ];
                $post['schedule'] = 7;
                $post['status'] = 1;
                break;
            case '92':
                if ($this->request->user['type'] != 10 && $this->request->user['type'] != 11 && $this->request->user['type'] != 4 && $this->request->user['type'] != 5) {
                    $this->result([], 1, '无权操作此项');
                }
                if ($this->request->user['type'] != 10 && $this->request->user['type'] != 11 && $this->request->user_id != $order['suid']) {
                    $this->result([], 1, '无权操作此项');
                }
                if ($order['bicloses'] != 1) {
                    $this->result([], 1, '已处于闭店调查中');
                }
                $post['bicloses'] = 2;
                $guanli = (new Users())->whereNotNull('openid')->where(['type' => [4, 5], 'del' => 1])->select();
                if ($this->request->user['type'] == 10  || $this->request->user['type'] == 11) {
                    foreach ($guanli as $guanlis) {
                        $message[] = [
                            'orderid' => $order['id'],
                            'user_id' =>  $guanlis['id'],
                            'ouser_id' => 0,
                            'status' => $order['schedule'],
                            'endstatus' => $order['schedule'],
                            'text' => '售后对客户' . $order['name'] . '发起闭店调查'
                        ];
                    }
                }
                break;
            case '93':
                if ($this->request->user['type'] != 10 && $this->request->user['type'] != 11 && $this->request->user['type'] != 4 && $this->request->user['type'] != 5) {
                    $this->result([], 1, '无权操作此项');
                }
                if ($this->request->user['type'] != 10 && $this->request->user['type'] != 11 && $this->request->user_id != $order['suid']) {
                    $this->result([], 1, '无权操作此项');
                }
                $post['schedule'] = 9;
                $post['status'] = 5;
                $guanli = (new Users())->whereNotNull('openid')->where(['type' => [4, 5], 'del' => 1])->select();
                if ($this->request->user['type'] != 10 || $this->request->user['type'] != 11) {
                    foreach ($guanli as $guanlis) {
                        $message[] = [
                            'orderid' => $order['id'],
                            'user_id' =>  $guanlis['id'],
                            'ouser_id' => 0,
                            'status' => $order['schedule'],
                            'endstatus' => $order['schedule'],
                            'text' => '售后已将客户' . $order['name'] . '店铺状态变更为闭店'
                        ];
                    }
                }
                break;
            case '95':
                if ($this->request->user['type'] != 6) {
                    $this->result([], 1, '无权操作此项');
                }
                if (empty($data['ishuo']) || empty($data['isfirst'])) {
                    $this->result([], 1, '请填写发货状态');
                }
                if (!empty($data['isfirst']) && empty($data['firsttimes'])) {
                    $this->result([], 1, '请填写首单发货日期');
                }
                $post['ishuo'] = $data['ishuo'];
                $post['isfirst'] = $data['isfirst'];
                $post['firsttimes'] = $data['firsttimes'] ?? '';
                if ($data['ishuo'] == 2 || $data['isfirst'] == 2) {
                    $post['ck'] = 2;
                }
                if ($data['ishuo'] != $order['ishuo'] || $data['isfirst'] != $order['isfirst'] || $data['firsttimes'] != $order['firsttimes']) {
                    $guanli = (new Users())->where(['type' => 5, 'del' => 1])->select();
                    foreach ($guanli as $guanlis) {
                        $message[] = [
                            'orderid' => $order['id'],
                            'user_id' =>  $guanlis['id'],
                            'ouser_id' => 0,
                            'status' => $order['schedule'],
                            'endstatus' => $order['schedule'],
                            'text' => '仓库变更任务发货信息，请查看',
                        ];
                    }
                }
                break;
            case '96':
                if ($this->request->user['type'] != 4) {
                    $this->result([], 1, '无权操作此项');
                }
                // if (empty($data['ordertypeid'])) {
                //     $this->result([], 1, '请选择派单类型');
                // }
                if (empty($data['ctype']) || ($data['ctype'] != 1 && $data['ctype'] != 2)) {
                    $this->result([], 1, '请选择是否计入门店');
                }
                if (empty($data['remark'])) {
                    $this->result([], 1, '请填写派单备注');
                }
                if (!empty($data['datetype'])) {
                    switch ($data['datetype']) {
                        case '1':
                            $post['xtimes'] = '';
                            if ($order['schedule'] >= 1 && $order['schedule'] < 3) {
                                $post['schedule'] = 1;
                            }
                            break;
                        case '2':
                            if (empty($data['xtimes'])) {
                                $this->result([], 1, '请填写选址出发日期');
                            }
                            $post['xtimes'] = $data['xtimes'];
                            break;
                        default:
                            $this->result([], 1, '类型错误');
                            break;
                    }
                }
                $post['baoxiaosons'] = $data['baoxiaosons'] ?? 1;
                $post['ordertype'] = $data['ordertypeid'] ?? 0;
                $post['yremark'] = $data['remark'];
                $post['ctype'] = $data['ctype'];
                if (!empty($data['name'])) {
                    $post['name'] = $data['name'];
                }
                if (!empty($data['mobile'])) {
                    $post['phone'] = $data['mobile'];
                }
                if (!empty($data['name2'])) {
                    $post['name2'] = $data['name2'];
                }
                if (!empty($data['mobile2'])) {
                    $post['phone2'] = $data['mobile2'];
                }
                if (empty($order['oldordertype']) && !empty($post['ordertype']) && $order['schedule'] <= 3) {
                    $post['oldordertype'] = $post['ordertype'];
                }
                if (!empty($data['weikuan'])) {
                    $post['weikuan'] = $data['weikuan'];
                }
                break;
            case '103':
                //选址审核通过
                if ($this->request->user['type'] != 4) {
                    $this->result([], 1, '无权操作此项');
                }
                $order = (new Business())->where(['id' => $data['id']])->find();
                if (empty($order)) {
                    $this->result([], 1, '订单不存在');
                }
                $message = [];
                $post = [];
                $post['isshenhe'] = 1;
                if ($order['schedule'] == 2) {
                    if ($order['foundation'] == 1) {
                        $post['schedule'] = 3;
                        $post['status'] = 2;
                    }
                    if ($order['foundation'] == 2 && $order['contract'] == 2) {
                        $post['schedule'] = 3;
                        $post['status'] = 2;
                        $message[] = [
                            'orderid' => $order['id'],
                            'user_id' =>  $order['suid'],
                            'ouser_id' => 0,
                            'status' => $order['schedule'],
                            'endstatus' => $order['schedule'],
                            'text' => '您的售后单选址完成，请填写信息',
                        ];
                    }
                    $message[] = [
                        'orderid' => $order['id'],
                        'user_id' =>  $order['duid'],
                        'ouser_id' => 0,
                        'status' => $order['schedule'],
                        'endstatus' => $order['schedule'],
                        'text' => '选址审核通过，可前往补充合同或查看状态',
                    ];
                } else {
                    $message[] = [
                        'orderid' => $order['id'],
                        'user_id' =>  $order['duid'],
                        'ouser_id' => 0,
                        'status' => $order['schedule'],
                        'endstatus' => $order['schedule'],
                        'text' => '选址信息审核通过，可前往补充合同信息或查看状态',
                    ];
                }
                break;
            case '104':
                //选址审核通过
                if ($this->request->user['type'] != 4) {
                    $this->result([], 1, '无权操作此项');
                }
                $order = (new Business())->where(['id' => $data['id']])->find();
                if (empty($order)) {
                    $this->result([], 1, '订单不存在');
                }
                $message = [];
                $post = [];
                $post['isshenhe'] = 3;
                $message[] = [
                    'orderid' => $order['id'],
                    'user_id' =>  $order['duid'],
                    'ouser_id' => 0,
                    'status' => $order['schedule'],
                    'endstatus' => $order['schedule'],
                    'text' => '您的选址信息审核驳回，请联系管理员',
                ];
                break;
            case '105':
                //选址审核通过
                if ($this->request->user['type'] != 4) {
                    $this->result([], 1, '无权操作此项');
                }
                $order = (new Business())->where(['id' => $data['id']])->find();
                if (empty($order)) {
                    $this->result([], 1, '订单不存在');
                }
                $message = [];
                $post = [];
                $post['schedule'] = 8;
                $message[] = [
                    'orderid' => $order['id'],
                    'user_id' =>  $order['duid'],
                    'ouser_id' => 0,
                    'status' => $order['schedule'],
                    'endstatus' => $post['schedule'],
                    'text' => '您的任务单已取消，如有疑问请联系管理员',
                ];
                if ($order['duid'] > 0) {
                    $userstatus[] = [
                        'type' => 1,
                        'user_id' => $order['duid'],
                        'status' => 2,
                        'orderid' =>  $order['id'],
                    ];
                }
                break;
            case '106':
                //选址审核通过
                if ($this->request->user['type'] != 4) {
                    $this->result([], 1, '无权操作此项');
                }
                $order = (new Business())->where(['id' => $data['id']])->find();
                if (empty($order)) {
                    $this->result([], 1, '订单不存在');
                }
                $message = [];
                $post = [];
                $post['svip'] =  $data['type'] == 2 ? 1 : 2;
                $post['viptext'] =  $data['text'];
                if ($post['svip'] == 2 && empty($post['viptext'])) {
                    $this->result([], 1, '描述不能为空');
                }
                break;
            case '107':
                //尾款全款审核
                if ($this->request->user['type'] != 4) {
                    $this->result([], 1, '无权操作此项');
                }
                $order = (new Business())->where(['id' => $data['id']])->find();
                if (empty($order)) {
                    $this->result([], 1, '订单不存在');
                }
                $message = [];
                $post = [];
                if (empty($data['type'])) {
                    $this->result([], 1, '操作选项错误');
                }
                $post['weikuanstatus'] = 1;
                if ($data['type'] == 2) {
                    $post['weikuan'] = $order['weikuanback'];
                }
                break;
            case '108':
                //0定金审核
                if ($this->request->user['type'] != 4) {
                    $this->result([], 1, '无权操作此项');
                }
                $order = (new Business())->where(['id' => $data['id']])->find();
                if (empty($order)) {
                    $this->result([], 1, '订单不存在');
                }
                $message = [];
                $post = [];
                $post['qkqueren'] = 2;
                break;
            case '109':
                if ($this->request->user['type'] != 9) {
                    $this->result([], 1, '无权操作此项');
                }
                $order = (new Business())->where(['id' => $data['id']])->find();
                if (empty($order)) {
                    $this->result([], 1, '订单不存在');
                }
                $message = [];
                $post = [];
                $post['suid'] = $data['uid'] ?? 0;
                if (empty($post['suid'])) {
                    $this->result([], 1, '请选择人员');
                }
                if ($post['suid'] == $order['suid'] && $order['suid'] != 0) {
                    $this->result([], 1, '售后人员未变更');
                }
                //验证权限
                $shouhouyzs = (new Users())->where(['type' => 3, 'del' => 1, 'id' => $post['suid']])->where("FIND_IN_SET (" . $order['type'] . ",groups)")->find();
                if (empty($shouhouyzs)) {
                    $this->result([], 1, '选中人员不存在或无该组权限');
                }
                $message[] = [
                    'orderid' => $data['id'],
                    'user_id' =>  $post['suid'],
                    'ouser_id' => $order['suid'],
                    'status' => $order['schedule'],
                    'endstatus' => $order['schedule'],
                    'text' => '您有新的售后任务单，请注意跟进'
                ];
                $message[] = [
                    'orderid' => $data['id'],
                    'user_id' =>  $order['suid'],
                    'ouser_id' => $post['suid'],
                    'status' => $order['schedule'],
                    'endstatus' => $order['schedule'],
                    'text' => '此任务单已取消您的售后身份，请留意'
                ];
                break;
            default:
                $this->result([], 1, '状态错误,请重试');
                break;
        }
        $model = new Business();
        Db::startTrans();
        try {
            $res = $model->allowfield(true)->save($post, ['id' => $data['id']]);
            if (count($message) > 0) {
                (new Messages())->allowfield(true)->saveAll($message);
            }
            if (count($userstatus) > 0) {
                foreach ($userstatus as $sgetuser) {
                    (new Userstatus())->UserStatus_m($sgetuser['user_id'], $sgetuser['type'], $sgetuser['orderid'], $sgetuser['status']);
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->result([], 1, '操作失败，请重试');
        }
        $this->result([], 0, '操作成功');
    }


    //任务列表
    public function orderlists()
    {
        $data = $this->request->get();
        $page = $data['page'] ?? 1;
        $limit =  $data['limit'] ?? 5;
        $page = (int)$page;
        $limit = (int)$limit;
        $lat = (float)$this->request->get('lat', 0) ?? 0;
        $lng = (float)$this->request->get('lng', 0) ?? 0;
        if (!empty($lat) && !empty($lng)) {
            if ($lat != 'undefined' && $lng != 'undefined') {
                Redis::zAdd('getlatlonarrs' . $this->request->user_id, time(), $lng . ',' . $lat);
            }
        }
        $where = [];
        $where1 = [];
        $where2 = [];
        $where[] = ['old', 'in', [2, 3]];
        $where[] = ['status', 'in', [1, 2, 3, 4]];
        if (!empty($data['status'])) {
            $sorts = ['schedule' => 'asc', 'times' => 'desc', 'created' => 'desc'];
            if ($data['status'] == 103) {
                $where[] = ['isshenhe', '=', 2];
                $where[] = ['schedule', 'in', [1, 2, 3]];
                $sorts = ['xcreated' => 'desc'];
            } elseif ($data['status'] == 99) {
                $where[] = ['schedule', '=', 2];
                $where[] = ['xcreated', '<=', date('Y-m-d', time() - 15 * 86400)];
                $sorts = ['xcreated' => 'desc'];
            } elseif ($data['status'] == 98) {
                $where[] = ['schedule', 'in', [2, 3, 4, 5, 6, 7, 8]];
                $sorts = ['xcreated' => 'desc'];
            } elseif ($data['status'] == 97) {
                $where[] = ['schedule', 'in', [2, 3, 4, 5, 6]];
                $where[] = ['suid', '=', 0];
                $sorts = ['xcreated' => 'desc'];
            } else {
                $where[] = ['schedule', '=', $data['status']];
            }
            if ($data['status'] == 1) {
                $sorts = ['xtimes' => 'asc'];
            }
            if ($data['status'] == 4) {
                $sorts = ['zhuangxiu' => 'desc', 'ishuo' => 'desc', 'isfirst' => 'desc'];
            }
        } else {
            if ($this->request->user['type'] == 2) {
                $sorts = ['ycreated' => 'desc', 'xcreated' => 'desc', 'id' => 'desc'];
            } else {
                $sorts = ['istop' => 'desc', 'xtimes' => 'desc', 'schedule' => 'asc', 'times' => 'desc', 'created' => 'desc'];
            }
            $where[] = ['schedule', 'in', [1, 2, 3, 4, 5, 6]];
        }
        switch ($this->request->user['type']) {
            case '12':
                $where[] = ['yuid', '=', $this->request->user_id];
                break;
            case '13':
                $where[] = ['yuid', '=', $this->request->user_id];
                break;
            case '2':
                break;
            case '10':
                $where[] = ['suid', '=', $this->request->user_id];
                break;
            case '11':
                $where[] = ['suid', '=', $this->request->user_id];
                break;
            case '4':
                break;
            case '5':
                break;
            case '6':
                $where[] = ['schedule', 'in', [3, 4, 5]];
                $where[] = ['ordertype', 'in', [1, 2, 3, 4, 5, 11]];
                $where[] = ['ctype', 'in', [1]];
                break;
            case '7':
                $where[] = ['schedule', 'in', []];
                $where[] = ['ordertype', 'in', [1, 2, 3, 4, 5, 8, 11, 12, 13, 14]];
                $where[] = ['ctype', 'in', [1]];
                $groups = [];
                if (!empty($this->request->user['groups'])) {
                    $groups = explode(',', $this->request->user['groups']) ?? [];
                }
                $where[] = ['type', 'in', $groups];
                $sorts = ['times' => 'desc', 'xtimes' => 'desc', 'created' => 'desc'];
                if (!empty($data['status']) && $data['status'] <= 2) {
                    $sorts = ['xtimes' => 'desc', 'created' => 'desc'];
                }
                if (!empty($data['status']) && $data['status'] >= 4) {
                    $sorts = ['kdates' => 'desc', 'times' => 'desc', 'created' => 'desc'];
                }
                break;
            case '8':
                $where[] = ['schedule', 'in', [2, 3, 4, 5, 6, 7]];
                $where[] = ['ordertype', 'in', [1, 2, 3, 4, 5, 8, 11, 12, 13, 14]];
                $where[] = ['ctype', 'in', [1]];
                $groups = [];
                if (!empty($this->request->user['groups'])) {
                    $groups = explode(',', $this->request->user['groups']) ?? [];
                }
                $where[] = ['type', 'in', $groups];
                $sorts = ['times' => 'desc', 'xtimes' => 'desc', 'created' => 'desc'];
                if (!empty($data['status']) && $data['status'] <= 2) {
                    $sorts = ['xtimes' => 'desc', 'created' => 'desc'];
                }
                if (!empty($data['status']) && $data['status'] >= 4) {
                    $sorts = ['kdates' => 'desc', 'times' => 'desc', 'created' => 'desc'];
                }
                break;
            case '9':
                $where[] = ['schedule', 'in', [2, 3, 4, 5, 6, 7]];
                $where[] = ['ordertype', 'in', [1, 2, 3, 4, 5, 8, 11, 12, 13, 14]];
                $where[] = ['ctype', 'in', [1]];
                $groups = [];
                if (!empty($this->request->user['groups'])) {
                    $groups = explode(',', $this->request->user['groups']) ?? [];
                }
                $where[] = ['type', 'in', $groups];
                $sorts = ['times' => 'desc', 'xtimes' => 'desc', 'created' => 'desc'];
                if (!empty($data['status']) && $data['status'] <= 2) {
                    $sorts = ['xtimes' => 'desc', 'created' => 'desc'];
                }
                if (!empty($data['status']) && $data['status'] >= 4) {
                    $sorts = ['kdates' => 'desc', 'times' => 'desc', 'created' => 'desc'];
                }
                break;
            default:
                $this->result([], 0, '无权限');
                break;
        }
        if (!empty($data['daterange'])) {
            $range = explode(',', $data['daterange']);
            if (count($range) < 2) {
                $where[] = ['created', 'between time', []];
            } else {
                $where[] = ['created', 'between time', [$range[0], $range[count($range) - 1]]];
            }
        }
        if (!empty($data['weikuan'])) {
            $where[] = ['weikuan', '=', $data['weikuan']];
        }
        if (!empty($data['typeid'])) {
            $where[] = ['type', '=', $data['typeid']];
        }
        if (!empty($data['huojia'])) {
            $where[] = ['ishuo', '=', $data['huojia']];
        }
        if (!empty($data['shoudan'])) {
            $where[] = ['isfirst', '=', $data['shoudan']];
        }
        if (!empty($data['zhaungxiu'])) {
            $where[] = ['zhuangxiu', '=', $data['zhaungxiu']];
        }
        if (!empty($data['shanghuo'])) {
            $where[] = ['shanghuo', '=', $data['shanghuo']];
        }
        if (!empty($data['anzhuang'])) {
            $where[] = ['huozhuang', '=', $data['anzhuang']];
        }
        if (!empty($data['weikuanstatus'])) {
            $where[] = ['weikuanstatus', '=', $data['weikuanstatus']];
            $sorts = ['kyupdated' => 'desc', 'htupdated' => 'desc'];
        }
        if (!empty($data['dingjin'])) {
            $where[] = ['qktype', '=', 1];
            $where[] = ['qkqueren', '=', 1];
        }
        if ($this->request->user_id == 261) {
            $where[] = ['duid', '>', 0];
        }
        $where2 = $where;
        // if ($this->request->user['type'] == 2) {
        //     $where[] = ['duid|kuid', '=', $this->request->user_id];
        // }
        $where1 = $where;
        //合并查询协选
        $xxser1 = [];
        $xxser2 = [];
        if (!empty($data['keywords'])) {
            $where[] = ['title|name|name2|htqdr|phone2|phone|address|getaddress|province|city|area|areas', 'like', '%' . $data['keywords'] . '%'];
            //查询对应的负责人ID
            $users = (new Users())->where('account|mobile', 'like', '%' . $data['keywords'] . '%')->column('id') ?? [];
            if (count($users) > 0) {
                $where1[] = ['yuid|suid|duid|kuid', 'in', $users];
                $where2[] = ['yuid|suid|duid|kuid', 'in', $users];
                $eeorderid = (new Businessxq())->where(['user_id' => $users, 'type' => 1])->column('orderid') ?? [];
                if (count($eeorderid) > 0) {
                    $xxser1 = $eeorderid;
                }
            } else {
                $where1[] = ['title|name2|htqdr|phone2|name|phone|address|getaddress|province|city|area|areas', 'like', '%' . $data['keywords'] . '%'];
                $where2[] = ['title|name2|htqdr|phone2|name|phone|address|getaddress|province|city|area|areas', 'like', '%' . $data['keywords'] . '%'];
            }
        }
        // if ($this->request->user['type'] == 2) {
        //     $xxser2 = (new Businessxq())->where(['user_id' => $this->request->user_id, 'type' => 1])->column('orderid') ?? [];
        //     $xorderid = array_merge($xxser1, $xxser2);
        //     if (count($xorderid) > 0) {
        //         $where2[] = ['id', 'in', $xorderid];
        //     } else {
        //         $where2[] = ['id', 'in', [0]];
        //     }
        // }
        $result = (new Business())->limit($limit)
            ->page($page)->order($sorts)
            ->whereOr(function ($query) use ($where) {
                $query->where($where);
            })->whereOr(function ($query) use ($where1) {
                $query->where($where1);
            })->whereOr(function ($query) use ($where2) {
                $query->where($where2);
            })->field('backdata', true)->select();
        foreach ($result as $k => $shop) {
            $shop['biclose'] = 1; //1不可操作取消 2可操作取消
            if (($this->request->user['type'] == 4 || $this->request->user['type'] == 5) && $shop['schedule'] <= 3) {
                $shop['biclose'] = 2; //1不可操作取消 2可操作取消
            }
            $shop['dingorxuan'] = $shop['ordertype'];
            if ($shop['ordertype'] == 12) {
                $shop['dingorxuan'] = 2;
            }
            if ($this->request->user['type'] != 2) {
                $shop['ytypes_text'] = config()["config"]['ytypes'][$shop['ytypes']] ?? '';
            }
            if ($shop['qktype'] > 0) {
                $shop['jntype_text'] = config()["config"]['jntype'][$shop['qktype']] ?? '';
            }
            $shop['ytypeslist_text'] = config()["config"]['ytypeslist'][$shop['ytypeslist']] ?? '';
            $shop['schedule_text'] = config()["config"]['schedule_text'][$shop['schedule']] ?? '';
            $shop['ordertype_text'] = config()["config"]['ordertype'][$shop['ordertype']] ?? '类型待定';
            if ($shop['ordertype'] == 3 && $shop['ctype'] == 2) {
                $shop['ordertype_text'] = '二次测量';
            }
            if ($shop['schedule'] == 2 && ($shop['foundation'] == 2 || $shop['contract'] == 2)) {
                $shop['schedule_text'] = $shop['schedule_text'] . '(已传部分资料)';
            }
            //售后经理信息
            $shouhou = (new Users())->where('id', $shop['suid'])->find();
            $shop['shouhuo'] = $shouhou['account'] ?? '无'; //售后经理
            $shop['shouhuo_mobile'] = $shouhou['mobile'] ?? ''; //售后经理电话
            //选址督导信息
            $dudao = (new Users())->where('id', $shop['duid'])->find();
            $shop['dudao'] = $dudao['account'] ?? '无'; //选址督导
            $shop['dudao_mobile'] = $dudao['mobile'] ?? ''; //选址督导电话
            //业务经理信息
            $yewu = (new Users())->where('id', $shop['yuid'])->find();
            $shop['yewu'] = $yewu['account'] ?? '无'; //业务经理
            $shop['yewu_mobile'] = $yewu['mobile'] ?? ''; //业务经理电话
            //开业督导信息
            $kaiye = (new Users())->where('id', $shop['kuid'])->find();
            $shop['kaiye'] = $kaiye['account'] ?? '无'; //开业督导
            $shop['kaiye_mobile'] = $kaiye['mobile'] ?? ''; //开业督导电话
            $shop['type_name'] = config()["config"]['type'][$shop['type']] ?? '';
            $shop['images'] = json_decode($shop['images'] ?? '', true) ?? [];
            $shop['images1'] = json_decode($shop['images1'] ?? '', true) ?? [];
            $shop['images2'] = json_decode($shop['images2'] ?? '', true) ?? [];
            $shop['images3'] = json_decode($shop['images3'] ?? '', true) ?? [];
            $shop['images4'] = json_decode($shop['images4'] ?? '', true) ?? [];
            $shop['images5'] = json_decode($shop['images5'] ?? '', true) ?? [];
            $shop['images6'] = json_decode($shop['images6'] ?? '', true) ?? [];
            $shop['images7'] = json_decode($shop['images7'] ?? '', true) ?? [];
            $shop['images9'] = json_decode($shop['images9'] ?? '', true) ?? [];
            $shop['images10'] = json_decode($shop['images10'] ?? '', true) ?? [];
            $shop['images11'] = json_decode($shop['images11'] ?? '', true) ?? [];
            $shop['images12'] = json_decode($shop['images12'] ?? '', true) ?? [];
            $shop['dplist'] = json_decode($shop['dplist'] ?? '', true) ?? [];
            $shop['sginfo'] = json_decode($shop['sginfo'] ?? '', true) ?? [];
            $shop['video'] = json_decode($shop['video'] ?? '', true) ?? [];
            $shop['video1'] = json_decode($shop['video1'] ?? '', true) ?? [];
            $shop['video3'] = json_decode($shop['video3'] ?? '', true) ?? [];
            $shop['video4'] = json_decode($shop['video4'] ?? '', true) ?? [];
            $shop['video5'] = json_decode($shop['video5'] ?? '', true) ?? [];
            $shop['video6'] = json_decode($shop['video6'] ?? '', true) ?? [];
            $shop['xxlist'] = []; //协选人员列表
            $shop['xiexuan'] = 1;
            $xxlist = [];
            if ($this->request->user['type'] == 8) {
                $shop['phone'] = '不显示';
                $shop['images5'] = [];
                $shop['images11'] = [];
                $shop['images2'] = [];
                $shop['images6'] = [];
                $shop['images7'] = [];
                $shop['dplist'] = [];
                $shop['yremark'] = '';
                $shop['dremark'] = '';
                $shop['xremark'] = '';
                $shop['sremark'] = '';
                $shop['givermeark'] = '';
                $shop['maoli'] = '';
                $shop['zongshu'] = '';
                $shop['xuanzhirmeark'] = '';
                $shop['ytypes_text'] = '';
                $shop['ytypeslist_text'] = '';
            }
            $shop['upaddress'] = 1;
            if ($this->request->user['type'] == 12 || $this->request->user['type'] == 13) {
                $shop['upaddress'] = 2;
            }
            //协选人员
            $xxhave = (new Businessxq())->where(['orderid' => $shop['id'], 'type' => 1])->column('user_id') ?? [];
            if (count($xxhave) > 0) {
                foreach ($xxhave as $ks => $xxuser) {
                    $xxusers = (new Users())->where('id', $xxuser)->find();
                    if (!empty($xxusers)) {
                        $xxlist[] = $xxusers['account'] . '(' . $xxusers['mobile'] . ')' ?? '';
                        if ($xxusers['id'] == $this->request->user_id) {
                            $shop['xiexuan'] = 2;
                        }
                    }
                }
            }
            $shop['xxlist'] = $xxlist; //协选人员列表
            //仓库确认发货入口
            $shop['ckcan'] = 0;
            if ($this->request->user['type'] == 6 && $shop['ishuo'] == 2 && $shop['isfirst'] == 2) {
                $shop['ckcan'] = 1;
            }
            //选址可报销提交次数
            $shop['dcan'] = 0;
            //开业可报销提交次数
            $shop['kcan'] = 0;
            if ($this->request->user['type'] == 2) {
                $shop['duid'] = $this->request->user_id;
                $shop['xiexuan'] = 1;
                if ($shop['schedule'] == 1) {
                    $shop['schedule'] = 2;
                }
                $shop['ytypeslist_text'] = '';
                $fxhave = (new Businessxq())->where(['user_id' => $this->request->user_id, 'orderid' => $shop['id'], 'type' => 1])->count() ?? 0;
                //选址是否已提交报销
                if ($shop['schedule'] >= 2 && ($shop['duid'] == $this->request->user_id || $fxhave > 0)) {
                    $ll = (new Reimburs())->where(['orderid' => $shop['id'], 'old' => 1, 'user_id' => $this->request->user_id, 'status' => [1, 2], 'type' => 1])->count();
                    if ($ll <= 0) {
                        $shop['dcan'] = 1;
                    }
                }
                //开业是否已提交报销
                if ($shop['schedule'] >= 5 && $shop['kuid'] == $this->request->user_id) {
                    $ll = (new Reimburs())->where(['orderid' => $shop['id'], 'old' => 1, 'user_id' => $this->request->user_id, 'status' => [1, 2], 'type' => 2])->count();
                    if ($ll <= 0) {
                        $shop['kcan'] = 1;
                    }
                }
                //到了开业步骤的单隐藏部分备注
                if ($shop['schedule'] >= 3) {
                    $shop['yremark'] = '';
                    $shop['dremark'] = '';
                    $shop['xremark'] = '';
                    $shop['xuanzhirmeark'] = '';
                }
            }
            $shop['xcolor'] = 1;
            if ((empty($shop['xtimes']) || $shop['xtimes'] == '0000-00-00') && $shop['schedule'] >= 1 && $shop['schedule'] < 3) {
                $shop['xtimes'] = '待定';
                $shop['xcolor'] = 2;
            }
            $shop['zpshouhou'] = 1; //1不可指派
            if ($this->request->user['type'] == 9 && $shop['schedule'] <= 6) {
                $shop['zpshouhou'] = 2;
            }
            // if($shop['duid'] == $this->request->user_id && $shop['kuid'] != $this->request->user_id && $shop['type'] == 2){
            //     unset($result[$k]);
            // }
        }
        //售后经理
        $dudaolist = [];
        if ($this->request->user['type'] == 4) {
            $dudaolist[] = ['id' => -1, 'name' => '暂不指派督导人员', 'del' => 1];
        }
        $dudao = (new Users())->where(['type' => 2, 'del' => 1])->field('id,account as name,del,status')->select();
        foreach ($dudao as $peoples) {
            if ($peoples['status'] == 1) {
                $peoples['name'] = $peoples['name'] . '(待单)';
            }
            if ($peoples['del'] == 2) {
                $peoples['name'] = $peoples['name'] . '(已删除)';
            }
            $dudaolist[] = $peoples;
        }
        //派单类型
        $ordertypelist = []; //全款类型
        $ordertype = config('config.ordertype');
        foreach ($ordertype as $k => $v) {
            $ordertypelist[] = ['id' => $k, 'name' => $v];
        }
        //计总
        $allnumber = (new Business())->whereOr(function ($query) use ($where) {
            $query->where($where);
        })->whereOr(function ($query) use ($where1) {
            $query->where($where1);
        })->whereOr(function ($query) use ($where2) {
            $query->where($where2);
        })->count();
        $this->result(['data' => $result, 'dudao' => $dudaolist, 'allnumber' => $allnumber, 'ordertypelist' => $ordertypelist], 0, '获取成功');
    }

    //任务单详情
    public function getdetail()
    {
        $id = $this->request->get('id/d', 0);
        $type = $this->request->get('type/d', 0);
        $shop = (new Business())->where('id', $id)->field('backdata', true)->find();
        if ($shop) {
            $areas = explode('&', $shop['areas'] ?? '');
            $shop['areas'] = $areas[0] ?? '';
            $shop['areas2'] = $areas[1] ?? '';
            $shop['shouhuo'] = (new Users())->where('id', $shop['suid'])->value('account') ?? '无'; //售后经理
            $shop['dudao'] = (new Users())->where('id', $shop['duid'])->value('account') ?? '无'; //选址督导
            $shop['yewu'] = (new Users())->where('id', $shop['yuid'])->value('account') ?? '无'; //业务经理
            $shop['kaiye'] = (new Users())->where('id', $shop['kuid'])->value('account') ?? '无'; //开业督导
            $shop['type_name'] = config()["config"]['type'][$shop['type']] ?? '';
            $shop['ordertype_name'] = config()["config"]['ordertype'][$shop['ordertype']] ?? '';
            $shop['images'] = json_decode($shop['images'] ?? '', true) ?? [];
            $shop['images1'] = json_decode($shop['images1'] ?? '', true) ?? [];
            $shop['images2'] = json_decode($shop['images2'] ?? '', true) ?? [];
            $shop['images3'] = json_decode($shop['images3'] ?? '', true) ?? [];
            $shop['images4'] = json_decode($shop['images4'] ?? '', true) ?? [];
            $shop['images5'] = json_decode($shop['images5'] ?? '', true) ?? [];
            $shop['images6'] = json_decode($shop['images6'] ?? '', true) ?? [];
            $shop['images7'] = json_decode($shop['images7'] ?? '', true) ?? [];
            $shop['images9'] = json_decode($shop['images9'] ?? '', true) ?? [];
            $shop['images10'] = json_decode($shop['images10'] ?? '', true) ?? [];
            $shop['images11'] = json_decode($shop['images11'] ?? '', true) ?? [];
            $shop['images12'] = json_decode($shop['images12'] ?? '', true) ?? [];
            $shop['sginfo'] = json_decode($shop['sginfo'] ?? '', true) ?? [];
            $shop['video'] = json_decode($shop['video'] ?? '', true) ?? [];
            $shop['video1'] = json_decode($shop['video1'] ?? '', true) ?? [];
            $shop['video3'] = json_decode($shop['video3'] ?? '', true) ?? [];
            $shop['video4'] = json_decode($shop['video4'] ?? '', true) ?? [];
            $shop['video5'] = json_decode($shop['video5'] ?? '', true) ?? [];
            $shop['video6'] = json_decode($shop['video6'] ?? '', true) ?? [];
            $shop['dplist'] = json_decode($shop['dplist'] ?? '', true) ?? [];
            //安装单检测是否存在安装单
            if (!empty($type) && $type == 1) {
                //开业单查询
                $shop['kai'] = 2;
                $have = (new Business())->where(['id' => $id, 'ordertype' => 5])->count();
                $have1 = (new Business())->where(['topid' => $id, 'ordertype' => 5])->count();
                if ($have > 0 || $have1 > 0) {
                    $shop['kai'] = 1;
                }
                //安装查询
                $shop['anzhuang'] = 2;
                $have = (new Business())->where(['id' => $id, 'ordertype' => 4])->count();
                $have1 = (new Business())->where(['topid' => $id, 'ordertype' => 4])->count();
                if ($have > 0 || $have1 > 0) {
                    $shop['anzhuang'] = 1;
                }
            }
            //安装单检测是否存在安装单
            if (!empty($type) && $type == 2) {
                //巡店单查询
                $shop['xun'] = 2;
                $have1 = (new Business())->where(['topid' => $id, 'ordertype' => 6])->count();
                if ($have1 > 0) {
                    $shop['xun'] = 1;
                }
                //回收查询
                $shop['hui'] = 2;
                $have1 = (new Business())->where(['topid' => $id, 'ordertype' => 7])->count();
                if ($have1 > 0) {
                    $shop['hui'] = 1;
                }
                //二开业查询
                $shop['erkai'] = 2;
                $have1 = (new Business())->where(['topid' => $id, 'ordertype' => 8])->count();
                if ($have1 > 0) {
                    $shop['erkai'] = 1;
                }
            }
        }
        $this->result($shop, 0, '获取成功');
    }



    public function getlatlon()
    {

        $lat = (float)$this->request->get('lat', 0) ?? 0;
        $lng = (float)$this->request->get('lng', 0) ?? 0;
        if (!empty($lat) && !empty($lng)) {
            if ($lat != 'undefined' && $lng != 'undefined') {
                Redis::zAdd('getlatlonarrs' . $this->request->user_id, time(), $lng . ',' . $lat);
            }
        }
        $id = $this->request->user_id;
        $startime = strtotime(date('Y-m-d'));
        $getlats = Redis::zRangeByScore('getlatlonarrs' . $id, $startime, time());
        $lists = [];
        $getlats = array_unique($getlats);
        foreach ($getlats as $k => &$getlat) {
            $time = Redis::zScore('getlatlonarrs' . $id, $getlat) ?? 0;
            $url = 'https://restapi.amap.com/v3/geocode/regeo';
            $text = '未知地址';
            $res = api_curl($url, ['location' => $getlat, 'key' => 'c400abfe779387dc8ded64d7db8dbbac', 'extensions' => 'all']);
            if (!empty($res['regeocode']['formatted_address'])) {
                $text = $res['regeocode']['formatted_address'];
            }
            if (!empty($res['regeocode']['aois'][0]['name'])) {
                $text = $res['regeocode']['aois'][0]['name'];
            }
            $getlat = explode(',', $getlat);
            if (count($getlat) < 2 || $getlat[0] == 'undefined') {
                unset($getlats[$k]);
            }
            $lists[] = [
                'latitude' => $getlat[1],
                'longitude' => $getlat[0],
                'desc' => date('Y-m-d H:i:s', $time),
                'title' => $text
            ];
        }
        $this->result($lists, 0, '操作成功');
    }

    public function login()
    {
        $data = $this->request->post();
        Log::write($data, 'test');
        $validate = new Validate([
            'mobile' => 'require',
            'password' => 'require',
        ], [
            'mobile.require' => '登陆账号不能为空',
            'password.require' => '登陆密码不能为空'
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $model = new Users();
        //判断用户是否已经注册
        $user = $model->where('account', $data['mobile'])->where('del', 1)->find();
        if (empty($user)) {
            $this->result([], 1, '账号不存在');
        }
        if ($user['password'] != md5(md5($data['password']))) {
            $this->result([], 1, '账号密码错误');
        }
        $token = 'user_' . md5(time() . $user['account']);
        Redis::setex($token, 30 * 86400, $user['id']);
        $this->result(['token' => $token], 0, '登录成功');
    }


    public function getaddress3()
    {
        $subcurr  = $this->request->get('subcurr');
        if (empty($subcurr)) {
            $lon  = $this->request->get('lon/f', '0');
            $lat  = $this->request->get('lat/f', '0');
            $page  = $this->request->get('page', 1);
            $filed = 'ROUND(6378.138*2*ASIN(SQRT(POW(SIN((' . $lat . '*PI()/180-lat*PI()/180)/2),2)+COS(' . $lat . '*PI()/180)*COS(lat*PI()/180)*POW(SIN((' . $lon . '*PI()/180-lon*PI()/180)/2),2)))*100)/100 AS dist';
            $result = (new Business())
                ->field('id,old,created,type,title,name,mobile,lat,lon,province,city,area,address,getaddress,times,status,bicloses,' . $filed)
                ->order('dist asc');
            $result = $result->whereOr(function ($query) {
                $query->where('ctype', 1)->where(['schedule' => [5, 6, 7], 'status' => [1, 2, 3, 4], 'bicloses' => [2]])->where('lat|lon', ">", 0)->where('type', "not in", [1, 2]);
            });
            $km = $this->request->user['km'] ?? 100;
            $km = (float)$km;
            $result = $result->page($page)->having('dist <= 30')->limit(15)->select();
            $statuslist[1] = '营业中';
            $statuslist[2] = '预备开业';
            $statuslist[3] = '可选店面';
            $statuslist[4] = '店面已删除';
            $statuslist[5] = '已闭店';
            foreach ($result as $shop) {
                $shop['km'] = $shop['dist'] . 'km';
                $shop['img'] = config()["config"]['img'][$shop['type']] ?? '';
                $shop['type'] = config()["config"]['type'][$shop['type']] ?? '';
                $shop['status_name'] = $statuslist[$shop['status']] ?? '';
                $zhaopai = (new Zhaopai())->where(['orderid' => $shop['id'], 'type' => 1])->find();
                if ($zhaopai) {
                    $zhaopai['images'] = json_decode($zhaopai['images'], true);
                }
                $shop['zhaopai'] = $zhaopai;
            }
            $this->result($result, 0, '获取成功');
        } else {
            $page  = $this->request->get('page', 1);
            $result = (new Zhaopai())->page($page)->limit(15)->alias('z')->field('z.id as zpid,z.status as zpstatus,b.province,b.city,b.area,b.id,b.type,b.name,b.mobile,b.address,b.getaddress,b.status,b.bicloses')->leftjoin('business b', 'z.orderid = b.id')->order('z.updated desc')->select();
            $statuslist[1] = '营业中';
            $statuslist[2] = '预备开业';
            $statuslist[3] = '可选店面';
            $statuslist[4] = '店面已删除';
            $statuslist[5] = '已闭店';
            foreach ($result as $shop) {
                $shop['img'] = config()["config"]['img'][$shop['type']] ?? '';
                $shop['type'] = config()["config"]['type'][$shop['type']] ?? '';
                $shop['status_name'] = $statuslist[$shop['status']] ?? '';
                $zhaopai = (new Zhaopai())->where(['id' => $shop['zpid']])->find();
                if ($zhaopai) {
                    $zhaopai['images'] = json_decode($zhaopai['images'], true);
                }
                $shop['zhaopai'] = $zhaopai;
            }
            $this->result($result, 0, '获取成功');
        }
    }

    public function getaddress()
    {
        $lon  = $this->request->get('lon/f', '0');
        $lat  = $this->request->get('lat/f', '0');
        $page  = $this->request->get('page', 1);
        $filed = 'ROUND(6378.138*2*ASIN(SQRT(POW(SIN((' . $lat . '*PI()/180-lat*PI()/180)/2),2)+COS(' . $lat . '*PI()/180)*COS(lat*PI()/180)*POW(SIN((' . $lon . '*PI()/180-lon*PI()/180)/2),2)))*100)/100 AS dist';
        $result = (new Business())
            ->field('id,old,created,type,title,name,mobile,lat,lon,province,city,area,address,getaddress,times,status,sginfo,' . $filed)
            ->order('dist asc');
        $result = $result->whereOr(function ($query) {
            $query->where('ctype', 1)->where(['status' => [1, 2, 3]])->where('lat|lon', ">", 0);
        })->whereOr(function ($query) {
            $query->where('ctype', 1)->where(['status' => 5])->where('lat|lon', ">", 0);
        });
        $km = $this->request->user['km'] ?? 100;
        $km = (float)$km;
        $result = $result->page($page)->having('dist <= ' . $km . ' and status = 5 or dist <= ' . $km . ' and status != 5')->limit(150)->select();
        $statuslist[1] = '营业中';
        $statuslist[2] = '预备开业';
        $statuslist[3] = '可选店面';
        $statuslist[4] = '店面已删除';
        $statuslist[5] = '已闭店';
        foreach ($result as $shop) {
            $shop['isziyou'] = 1;
            if ($this->request->user['type'] == 4 || $this->request->user['type'] == 5 || $this->request->user['yuancheng'] == 2) {
                $shop['isziyou'] = 2;
            }
            $sginfo = json_decode($shop['sginfo'], true) ?? [];
            $sglist = [];
            foreach ($sginfo as $sgrow) {
                if (!empty($sgrow['name']) || !empty($sgrow['mobile']) || !empty($sgrow['pinpai']) || !empty($sgrow['beizhu'])) {
                    $sglist[] = $sgrow;
                }
            }
            $shop['sginfo'] = $sglist;
            $shop['km'] = $shop['dist'] . 'km';
            $shop['img'] = config()["config"]['img'][$shop['type']] ?? '';
            $shop['type'] = config()["config"]['type'][$shop['type']] ?? '';
            $shop['status_name'] = $statuslist[$shop['status']] ?? '';
        }
        $result2 = (new Marks())
            ->field('id,title,lat,lon,reAddress,address,' . $filed)
            ->where(['status' => [1, 2]])
            ->order('dist asc')->page($page)->having('dist <= ' . $km)->limit(150)->select();
        foreach ($result2 as $shops) {
            $shops['isziyou'] = 1;
            $shops['sginfo'] = [];
            $shops['km'] = $shops['dist'] . 'km';
            $shops['status_name'] = '备选门面';
            $shops['name'] = '备选待使用门面';
            $shops['getaddress'] = $shops['reAddress'];
            $shops['province'] = '';
            $shops['city'] = '';
            $shops['area'] = '';
        }
        if (count($result) > 0) {
            $result = $result->toArray();
        } else {
            $result = [];
        }
        if (count($result2) > 0) {
            $result2 = $result2->toArray();
        } else {
            $result2 = [];
        }
        $resultall = array_merge($result, $result2);
        $ages = array_column($resultall, 'dist');
        array_multisort($ages, SORT_ASC, $resultall);
        $this->result($resultall, 0, '获取成功');
    }

    public function getaddress2()
    {
        $lon  = $this->request->get('lon/f', '0');
        $lat  = $this->request->get('lat/f', '0');
        $title  = $this->request->get('title');
        $filed = 'ROUND(6378.138*2*ASIN(SQRT(POW(SIN((' . $lat . '*PI()/180-lat*PI()/180)/2),2)+COS(' . $lat . '*PI()/180)*COS(lat*PI()/180)*POW(SIN((' . $lon . '*PI()/180-lon*PI()/180)/2),2)))*100)/100 AS dist';
        $result = (new Business())
            ->field('id,bicloses,schedule,foundation,contract,ordertype,old,created,type,title,name,mobile,lat,lon,province,city,area,address,getaddress,times,status,suid,' . $filed)
            ->order('dist asc');
        if (!empty($title)) {
            $result = $result->where('title|name|phone|phone2|mobile|province|city|area|getaddress|address', 'like', '%' . $title . '%');
        } else {
            $result = $result->having('dist <= 30');
        }
        $result = $result->limit(50)->where(['ordertype' => [1, 2, 3, 4, 5, 11, 12, 13, 14]])->where('ctype', 1)->where('schedule', '<>', 8)->where(['status' => [1, 2, 3]])->select();
        foreach ($result as $shop) {
            $shop['biclose'] = 1; //1不可操作闭店 2可操作闭店
            $shop['biclosedc'] = 1; //1不可操作闭店调查 2可操作闭店调查
            if ($this->request->user['type'] == 4 || $this->request->user['type'] == 5 && $shop['bicloses'] == 1) {
                $shop['biclose'] = 2; //1不可操作闭店 2可操作闭店
            }
            if (($this->request->user['type'] == 10 || $this->request->user['type'] == 11) && $shop['suid'] == $this->request->user_id && $shop['bicloses'] == 1) {
                $shop['biclose'] = 2; //1不可操作闭店 2可操作闭店
            }
            if (($this->request->user['type'] == 4 || $this->request->user['type'] == 5) && $shop['bicloses'] == 1) {
                $shop['biclosedc'] = 2;
            }
            if (($this->request->user['type'] == 10 || $this->request->user['type'] == 11) && $shop['suid'] == $this->request->user_id && $shop['bicloses'] == 1) {
                $shop['biclosedc'] = 2;
            }
            $shop['km'] = $shop['dist'] . 'km';
            $shop['type'] = config()["config"]['type'][$shop['type']] ?? '';
            $shop['iskai'] = 1;
            $shop['isxun'] = 1;
            if (empty($shop['lat']) || empty($shop['lat'])) {
                $shop['province'] = '';
                $shop['area'] = '';
                $shop['city'] = '';
                $shop['getaddress'] = '选址中';
                $shop['address'] = '(选址后才能进行开业、巡店等操作)';
            }
            if ($shop['old'] == 1) {
                if ($shop['status'] == 2 || $shop['status'] == 3) {
                    $shop['iskai'] = 2;
                }
                if ($shop['status'] == 1) {
                    $shop['isxun'] = 2;
                }
                $statuslist[1] = '营业中';
                $statuslist[2] = '预备开业';
                $statuslist[3] = '可选店面';
                $statuslist[4] = '店面已删除';
                $statuslist[5] = '停业';
                $shop['status_name'] = $statuslist[$shop['status']] ?? '';
            } else {
                if ($shop['schedule'] >= 3 && $shop['schedule'] <= 5) {
                    $shop['iskai'] = 2;
                }
                if ($shop['schedule'] >= 6 && $shop['schedule'] <= 8) {
                    $shop['isxun'] = 2;
                }
                if ($shop['ordertype'] == 4) {
                    $shop['iskai'] = 2;
                    $shop['isxun'] = 2;
                }
                $shop['status_name'] = config()["config"]['schedule_text'][$shop['schedule']] ?? '';
            }
            if ($shop['bicloses'] > 1) {
                $shop['status_name'] = '[闭店调查中]' . $shop['status_name'];
            }
            if ($shop['schedule'] == 2 && ($shop['foundation'] == 2 || $shop['contract'] == 2)) {
                $shop['status_name'] = $shop['status_name'] . '(当前仅传部分资料上传,未上传全部资料)';
            }
        }
        $this->result($result, 0, '获取成功');
    }

    public function getinfo()
    {

        //查看公告
        $chakanlist = [
            'allread' => 0, //全部公告未读
            'annous' => 0, //公告未读
            'study' => 0 //学习未读
        ];
        $readed = (new Annouslog())->where(['user_id' => $this->request->user_id])->column('annousid') ?? [];
        $sonstype = [0, 1, 2];
        if ($this->request->user['type'] == 2) {
            $sonstype = [0, $this->request->user['sonstype']];
        }
        $chakanlist['annous'] = (new Annous())->where(['sonstype' => $sonstype])->where(['leixin' => 1])->whereNotIn('id', $readed)->whereTime('enddates', '>=', date('Y-m-d'))
            ->field('id,dates,content,title')->order('id desc')->where("FIND_IN_SET (" . $this->request->user['type'] . ",type)")->count();
        $chakanlist['study'] = (new Annous())->where(['sonstype' => $sonstype])->where(['leixin' => 2])->whereNotIn('id', $readed)->whereTime('enddates', '>=', date('Y-m-d'))
            ->field('id,dates,content,title')->order('id desc')->where("FIND_IN_SET (" . $this->request->user['type'] . ",type)")->count();
        $chakanlist['allread']  = $chakanlist['annous'] + $chakanlist['study'];
        $schedule = config()["config"]['schedule_nav'];
        $schedules = [['id' => 0, 'name' => '全部']];
        $typelist = [['id' => 0, 'name' => '全部项目']];
        $tmpid = [
            'asQo-LK-Wp48XFLpbiAgAcLdhVdbjpvQEomm3WXllPI'
        ];
        // if ($this->request->user['type'] == 7) {
        //     $schedules = [];
        // }
        if ($this->request->user['type'] == 12 || $this->request->user['type'] == 13 || $this->request->user['type'] == 2) {
            $schedules[] = [
                'id' => 8,
                'name' => '回收单'
            ];
        }
        if ($this->request->user['type'] == 9) {
            $schedules[] = [
                'id' => 97,
                'name' => '待指派单'
            ];
        }
        foreach ($schedule as $k => $v) {
            if ($this->request->user['type'] == 6) {
                if ($k == 3 || $k == 4  || $k == 5) {
                    $schedules[] = [
                        'id' => $k,
                        'name' => $v
                    ];
                }
            }
            if ($this->request->user['type'] == 7) {
                if ($k == 1 || $k == 2  || $k == 4  || $k == 5) {
                    $schedules[] = [
                        'id' => $k,
                        'name' => $v
                    ];
                }
            } else {
                if ($k != 8) {
                    $schedules[] = [
                        'id' => $k,
                        'name' => $v
                    ];
                }
            }
        }
        if ($this->request->user['type'] == 4 || $this->request->user['type'] == 5) {
            $schedules[] = [
                'id' => 99,
                'name' => '选址或失败'
            ];
        }
        $daishenheo = 0;
        if ($this->request->user['type'] == 4) {
            $schedules[] = [
                'id' => 103,
                'name' => '选址待审核'
            ];
            $daishenheo = (new Business())->where(['isshenhe' => 2, 'schedule' => [1, 2, 3]])->count();
        }
        $dingjino = 0;
        if ($this->request->user['type'] == 4) {
            $dingjino = (new Business())->where(['qktype' => 1, 'qkqueren' => 1, 'status' => [1, 2, 3, 5]])->count();
        }
        $this->request->user['qrcode'] = '';
        $this->request->user['iscode'] = false;
        $this->request->user['iswxcode'] = false;
        $this->request->user['dingyue'] = false;
        $this->request->user['gzhcode'] = 'https://hbhmddapis.gxfacai888.cn/neqrcode.jpg';
        // if (empty($this->request->user['xcxopenid']) && $this->request->user['look'] == 1) {
        //     $this->request->user['iswxcode'] = true;
        // } elseif (!empty($this->request->user['xcxopenid']) && $this->request->user['look'] == 1) {
        //     $template = $this->request->user['template'];
        //     $template = json_decode($template ?? '', true) ?? [];
        //     if (empty($template[$tmpid[0]])) {
        //         $template[$tmpid[0]]['number'] = 0;
        //     }
        //     if ($template[$tmpid[0]]['number'] < 10) {
        //         $this->request->user['dingyue'] = true;
        //     }
        // }
        try {
            $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . config('wechat2.')['app_id'] . "&redirect_uri=https://"
                . Env('APP_API_URL')
                . "/Other/getOpenId?userid=" . $this->request->user_id . '&state=1&response_type=code&scope=snsapi_base#wechat_redirect';
            $savePath = $_SERVER['DOCUMENT_ROOT'] . '/uploads/qrcode/';
            $qrLevel = 'H';
            $qrSize = '8';
            if ($filename = createQRcode($savePath, $url, $qrLevel, $qrSize)) {
                $qcode = url('/uploads/qrcode/' . $filename, '', '', true);
                $this->request->user['qrcode'] = $qcode;
            }
        } catch (\Exception $e) {
        }
        if (empty($this->request->user['openid']) && $this->request->user['type'] != 6 && $this->request->user['old'] == 1 && $this->request->user['look'] == 1 && empty($this->request->user['xcxopenid'])) {
            $this->request->user['iscode'] = true;
        }
        $typeconfig = config()["config"]['type'];
        foreach ($typeconfig as $k => $v) {
            $typelist[] = [
                'id' => $k,
                'name' => $v
            ];
        }
        $lookdates = ['number' => 0, 'text' => '请确认每个客户的回款情况，并上传回款证明（收据）'];
        if ($this->request->user['type'] == 2) {
            //1-3号提示
            $ldates = (int)date('d');
            if ($ldates >= 1 && $ldates <= 3) {
                $ltimes = '01';
                if ((int)date('H') >= 14) {
                    $ltimes = '02';
                }
                $lookdates['number'] = (int)($ldates . $ltimes);
            }
        }
        $user = $this->request->user;
        if ($user['type'] == 2) {
            if ($user['status'] == 2) {
                $user['account'] = $user['account'] . '(忙)';
            } else {
                $user['account'] = $user['account'] . '(待)';
            }
        }
        $this->result(['dingjino' => $dingjino, 'daishenheo' => $daishenheo, 'lookdates' => $lookdates, 'chakanlist' => $chakanlist, 'user' => $user, 'schedule' => $schedules, 'typelist' => $typelist, 'tmpid' => $tmpid], 0, '获取成功');
    }

    public function other()
    {
        $isbx  = $this->request->get('bx/d', 0);
        $supertypelist = []; //人员类型
        $supertype = config('config.typepeople');
        foreach ($supertype as $k => $v) {
            $supertypelist[] = ['id' => $k, 'name' => $v];
        }
        $jntypelist = []; //全款类型
        $jntype = config('config.jntype');
        foreach ($jntype as $k => $v) {
            $jntypelist[] = ['id' => $k, 'name' => $v];
        }

        $hktypelist = []; //项目类型
        $hktype = config('config.hktype_text');
        foreach ($hktype as $k => $v) {
            $hktypelist[] = ['id' => $k, 'name' => $v];
        }
        $ytypeslists = []; //项目类型
        $ytypeslist = config('config.ytypeslist');
        foreach ($ytypeslist as $k => $v) {
            $ytypeslists[] = ['id' => $k, 'name' => $v];
        }
        $ytypem = []; //项目类型
        $ytypes = config('config.ytypes');
        foreach ($ytypes as $k => $v) {
            if ($k != 3) {
                $ytypem[] = ['id' => $k, 'name' => $v];
            }
        }
        $ordertypelist = []; //项目类型
        $ordertype = config('config.ordertype');
        foreach ($ordertype as $k => $v) {
            $ordertypelist[] = ['id' => $k, 'name' => $v];
        }
        $groups = [];
        if (!empty($this->request->user['groups'])) {
            $groups = explode(',', $this->request->user['groups']) ?? [];
        }
        //分组信息
        $type = config('config.type');
        $typelist = []; //项目类型
        foreach ($type as $k => $v) {
            $skcan = 1; //1表示可以选择售后 2表示不可以
            $sklis = (new Users())->where(['type' => 9, 'del' => 1])->where("FIND_IN_SET (" . $k . ",groups)")->count();
            if ($sklis > 0) {
                $skcan = 2;
            }
            if ($k != 99) {
                if (empty($groups)) {
                    $typelist[] = ['id' => $k, 'name' => $v, 'shouhou' => $skcan];
                } elseif ($this->request->user['groups'] == 0) {
                    $typelist[] = ['id' => $k, 'name' => $v, 'shouhou' => $skcan];
                } elseif (in_array($k, $groups)) {
                    $typelist[] = ['id' => $k, 'name' => $v, 'shouhou' => $skcan];
                }
            } elseif ($k == 99 && $isbx == 1) {
                $typelist[] = ['id' => $k, 'name' => $v, 'shouhou' => $skcan];
            }
        }
        //售后经理
        // if (!empty($groups)) {
        //     $people = (new Users())->where(['type' => 3, 'groups' => $groups,'del' => 1])->field('id,account as name,del')->select();
        // } else {
        //     $people = (new Users())->where(['type' => 3,'del' => 1])->field('id,account as name,del')->select();
        // }
        // foreach ($people as $peoples) {
        //     if ($peoples['del'] == 2) {
        //         $peoples['name'] = $peoples['name'] . '(账号已删除)';
        //     }
        // }
        $people = [];
        $shouhou = (new Users())->field('id,account as name,del,groups')->where(['del' => 1, 'type' => [10, 11]])->select() ?? [];
        foreach ($shouhou as $user) {
            if ($user['groups'] == 0) {
                $people[] = [
                    'id' => (string)$user['id'],
                    'name' => $user['name']
                ];
            } else {
                $sgroupsgive = explode(',', $user['groups']);
                $havjs = array_intersect($groups, $sgroupsgive);
                if (count($havjs) > 0) {
                    $people[] = [
                        'id' => (string)$user['id'],
                        'name' => $user['name']
                    ];
                }
            }
        }
        //业务经理
        $yewu = (new Users())->where(['type' => [12, 13], 'del' => 1])->field('id,account as name,del')->select();
        foreach ($yewu as $peoples) {
            if ($peoples['del'] == 2) {
                $peoples['name'] = $peoples['name'] . '(已删除)';
            }
        }
        //督导
        $dudao = (new Users())->where(['type' => 2, 'del' => 1])->field('id,account as name,del,status')->select();
        foreach ($dudao as $peoples) {
            if ($peoples['del'] == 2) {
                $peoples['name'] = $peoples['name'] . '(已删除)';
            }
            if ($peoples['status'] == 1) {
                $peoples['name'] = $peoples['name'] . '(待单)';
            }
        }
        //上个月合同
        $qishu = date('Ym', strtotime('-1 month'));
        $uporder = (new Uploadtk())->where(['user_id' => $this->request->user_id, 'qishu' => $qishu])->find() ?? [];
        if ($uporder) {
            $uporder['images'] = json_decode($uporder['images'], true) ?? [];
            $uporder['names'] = json_decode($uporder['names'], true) ?? [];
        }
        $this->result(['supertypelist' => $supertypelist, 'jntypelist' => $jntypelist, 'ytypem' => $ytypem, 'ytypeslists' => $ytypeslists, 'uporder' => $uporder, 'hktypelist' => $hktypelist, 'ordertypelist' => $ordertypelist, 'typelist' => $typelist, 'people' => $people, 'yewu' => $yewu, 'dudao' => $dudao], 0, '获取成功');
    }

    //业务经理派单或编辑任务单
    public function addyDispatch()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'id' => 'require',
            'xtimes' => 'require',
            'mobile' => 'require',
            'address' => 'require',
        ], [
            'id.require' => 'ID不能为空',
            'xtimes.require' => '出发日期不能为空',
            'mobile.require' => '客户电话不能为空',
            'address.require' => '区域及地址不能为空',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        if (!preg_match("/^1[0-9]{10}$/", $data['mobile'])) {
            $this->result([], 1, '手机格式不正确,请检查手机号是否正确或含有空格');
        }
        if (!empty($data['mobile2']) && !preg_match("/^1[0-9]{10}$/", $data['mobile2'])) {
            $this->result([], 1, '手机2格式不正确,请检查手机号是否正确或含有空格');
        }
        if (empty($data['mobile'])) {
            $this->result([], 1, '请填写客户手机号');
        }
        if (!empty($data['address']) && !empty($data['address2'])) {
            $data['address'] = $data['address'] . '&' . $data['address2'];
        }
        $post = [
            'phone' =>  $data['mobile'],
            'phone2' =>  $data['mobile2'] ?? '',
            'areas' => $data['address'],
            'xtimes' => $data['xtimes'] ?? '',
        ];
        $message = []; //通知数组
        $order = (new Business())->where(['id' => $data['id'], 'yuid' => $this->request->user_id])->find();
        if (empty($order)) {
            $this->result([], 1, '任务任务单不存在');
        }
        if ($order['schedule'] >= 3) {
            $this->result([], 1, '任务单已确认选址完成，如需修改状态请联系管理员');
        }
        $model = new Business();
        $res = $model->allowfield(true)->save($post, ['id' => $data['id']]);
        if ($res) {
            if (count($message) > 0) {
                (new Messages())->allowfield(true)->saveAll($message);
            }
            $this->result([], 0, '操作成功');
        }
        $this->result([], 1, '操作失败，请重试');
    }

    //业务经理派单或编辑任务单
    public function addDispatch()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'typeid' => 'require|gt:0',
            'ytypes' => 'require|gt:0',
            'name' => 'chs|length:2,10',
            'surname' => 'chs|length:1,10',
            'fame' => 'chs|length:1,10',
            'name2' => 'chs|length:2,10',
            'surname2' => 'chs|length:1,10',
            'fame2' => 'chs|length:1,10',
            'xtimes' => 'require',
            'mobile' => 'require',
            'address' => 'require',
            'remark' => 'require|length:30,9999',
        ], [
            'ytypes.require' => '派单类型不能为空',
            'ytypes.gt' => '派单类型不能为空',
            'xtimes.require' => '出发日期不能为空',
            'typeid.require' => '项目分组不能为空',
            'typeid.gt' => '项目分组不能为空',
            'surname.chs' => '客户姓只能是汉字,请勿填写其他或空格',
            'fame.length' => '客户姓名长度控制着1-10个字符',
            'surname.length' => '客户姓名长度控制着1-10个字符',
            'fame.chs' => '客户名只能是汉字,请勿填写其他或空格',
            'name.chs' => '客户姓名只能是汉字,请勿填写其他或空格',
            'name.length' => '客户姓名长度控制着2-10个字符',
            'surname2.chs' => '客户姓只能是汉字,请勿填写其他或空格',
            'fame2.length' => '客户姓名长度控制着1-10个字符',
            'surname2.length' => '客户姓名长度控制着1-10个字符',
            'fame2.chs' => '客户名只能是汉字,请勿填写其他或空格',
            'name2.chs' => '客户姓名只能是汉字,请勿填写其他或空格',
            'name2.length' => '客户姓名长度控制着2-10个字符',
            'mobile.require' => '客户电话不能为空',
            'address.require' => '区域及地址不能为空',
            'remark.require' => '备注信息不能为空',
            'remark.length' => '备注信息长度不能低于30个字符',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $data['shouhoutext'] = $data['shouhoutext'] ?? '';
        if ($data['shouhoutext'] == false && empty($data['shouhouid'])) {
            $this->result([], 1, '售后不能为空');
        }
        $data['remark'] = str_replace(' ', '', $data['remark']);
        if (mb_strlen($data['remark']) < 30) {
            $this->result([], 1, '备注长度当前为' . mb_strlen($data['remark']) . ',不得低于30个字符');
        }
        if ($data['ytypes'] == 1 || $data['ytypes'] == 2) {
            if (empty($data['ytypeslist'])) {
                $this->result([], 1, '请填写店铺信息选项');
            }
        }
        if (!preg_match("/^1[0-9]{10}$/", $data['mobile'])) {
            $this->result([], 1, '手机格式不正确,请检查手机号是否正确或含有空格');
        }
        //新添加项目需要单独填写姓、名
        if (empty($data['id']) && empty($data['name'])) {
            if (empty($data['surname']) || empty($data['fame'])) {
                $this->result([], 1, '请填写完整客户姓、名信息');
            }
            $data['name'] = $data['surname'] . $data['fame'];
        }
        if (empty($data['id']) && (!empty($data['surname2']) || !empty($data['fame2']))) {
            if (empty($data['surname2']) || empty($data['fame2'])) {
                $this->result([], 1, '请填写完整客户姓、名信息');
            }
            $data['name2'] = $data['surname2'] . $data['fame2'];
        }
        if (empty($data['name'])) {
            $this->result([], 1, '请填写客户姓名');
        }
        if (mb_substr($data['name'], -1, 1, 'utf-8') == '总') {
            $this->result([], 1, '请填写用户具体姓名，不要填写先生、老板、小姐、美女、女士、总等泛词');
        }
        if (strpos($data['name'], '总监') > 0 || strpos($data['name'], '先生') > 0 || strpos($data['name'], '美女') > 0 || strpos($data['name'], '女士') > 0 || strpos($data['name'], '老板') > 0 || strpos($data['name'], '小姐') > 0) {
            $this->result([], 1, '请填写用户具体姓名，不要填写先生、老板、小姐、美女、女士、总、总监等泛词');
        }
        if (!empty($data['name2'])) {
            if (mb_substr($data['name2'], -1, 1, 'utf-8') == '总') {
                $this->result([], 1, '请填写用户具体姓名，不要填写先生、老板、小姐、美女、女士、总等泛词');
            }
            if (strpos($data['name2'], '总监') > 0 || strpos($data['name2'], '先生') > 0 || strpos($data['name2'], '美女') > 0 || strpos($data['name2'], '女士') > 0 || strpos($data['name2'], '老板') > 0 || strpos($data['name2'], '小姐') > 0) {
                $this->result([], 1, '请填写用户具体姓名，不要填写先生、老板、小姐、美女、女士、总、总监等泛词');
            }
        }
        if (empty($data['mobile'])) {
            $this->result([], 1, '请填写客户手机号');
        }
        if (!empty($data['shouhouid'])) {
            $shouhou = (new Users())->where(['id' => $data['shouhouid'], 'del' => 1])->find();
            if (empty($shouhou)) {
                $this->result([], 1, '售后经理账号不存在，请重新选择');
            }
        }
        if (!empty($data['ytypes'])) {
            if (($data['ytypes'] == 1 || $data['ytypes'] == 2) && (empty($data['ytypeslist']) && empty($data['id']))) {
                $this->result([], 1, '店铺信息选项不能为空');
            }
            if (empty($data['ordertype']) && empty($data['id'])) {
                switch ($data['ytypes']) {
                    case '1':
                        $data['ordertype'] = 1;
                        break;
                    case '2':
                        $data['ordertype'] = 11;
                        break;
                    case '3':
                        $data['ordertype'] = 3;
                        $data['ytypeslist'] = 0;
                        break;
                    default:
                        # code...
                        break;
                }
                $data['ordertype'] = 0;
            }
        }
        if (!empty($data['ytypeslist']) && $data['ytypeslist'] == 2 && !empty($data['version'])) {
            //数据核验
            if (!is_array($data['dplist'])) {
                $this->result([], 1, '店铺数据类型错误，请重试');
            }
            if (count($data['dplist']) < 3) {
                $this->result([], 1, '店铺数据数量错误,请刷新重试');
            }
            foreach ($data['dplist'] as $k => $list) {
                if ($k == 0 && (empty($list['mianji']) || empty($list['address']) || empty($list['text']))) {
                    $this->result([], 1, '面积、地址、说明等信息都不能为空');
                }
            }
        } elseif (!empty($data['ytypeslist']) && in_array($data['ytypeslist'], [2, 3, 4, 5]) && !empty($data['version']) && $data['version'] >= 1.1) {
            //数据核验
            if (!is_array($data['dplist'])) {
                $this->result([], 1, '店铺数据类型错误，请重试');
            }
            if (count($data['dplist']) < 3) {
                $this->result([], 1, '店铺数据数量错误,请刷新重试');
            }
            foreach ($data['dplist'] as $k => $list) {
                if ($k == 0 && (empty($list['mianji']) || empty($list['address']) || empty($list['text']))) {
                    $this->result([], 1, '面积、地址、说明等信息都不能为空');
                }
            }
        } else {
            $data['dplist'] = [];
        }
        if ($this->request->user['type'] != 12 && $this->request->user['type'] != 13) {
            $this->result([], 1, '无此操作权限');
        }
        if (!empty($data['address']) && !empty($data['address2'])) {
            $data['address'] = $data['address'] . '&' . $data['address2'];
        }
        if (!empty($data['version']) && $data['version'] >= 1.2) {
            if (empty($data['zongshu'])) {
                $this->result([], 1, '告知客户总数不能为空');
            }
            if (empty($data['maoli'])) {
                $this->result([], 1, '告知客户毛利不能为空');
            }
        }
        if (empty($data['iswang'])) {
            $this->result([], 1, '请选择是否网签');
        }
        $post = [
            'old' => 2,
            'suid' => $data['shouhouid'] ?? 0,
            'type' => $data['typeid'],
            'name' => $data['name'],
            'name2' => $data['name2'] ?? '',
            'phone' =>  $data['mobile'],
            'phone2' =>  $data['mobile2'] ?? '',
            'areas' => $data['address'],
            'xtimes' => $data['xtimes'] ?? '',
            'yremark' => $data['remark'] ?? '',
            'ordertype' => $data['ordertype'] ?? 1,
            'ytypes' => $data['ytypes'] ?? 0,
            'ytypeslist' => $data['ytypeslist'] ?? 0,
            'ctype' => $data['ctype'] ?? 1,
            'qktype' => $data['qktype'] ?? 0,
            'iswang' =>  $data['iswang'] ?? 0,
            'dplist' =>  json_encode($data['dplist'] ?? [], true) ?? '',
            'zongshu' => $data['zongshu'] ?? '',
            'maoli' => $data['maoli'] ?? '',
        ];
        $message = []; //通知数组
        if ($this->request->user_id == 108) {
            dump($post);
            die;
        }
        //为空
        if (empty($data['id'])) {
            $post['user_id'] = $this->request->user_id;
            $post['yuid'] = $this->request->user_id;
            $post['schedule'] = 1;
            $post['status'] = 3;
        } else {
            $this->result([], 1, '已发布任务单暂不支持修改');
            $order = (new Business())->where(['id' => $data['id'], 'yuid' => $this->request->user_id])->find();
            if (empty($order)) {
                $this->result([], 1, '任务任务单不存在');
            }
            if ($order['schedule'] >= 3) {
                $this->result([], 1, '任务单已确认选址完成，如需修改状态请联系管理员');
            }
        }
        $model = new Business();
        if (!empty($data['id'])) {
            $res = $model->allowfield(true)->save($post, ['id' => $data['id']]);
            if ($post['suid'] != $order['suid']) {
                $message[] = [
                    'orderid' => $data['id'],
                    'user_id' =>  $post['suid'],
                    'ouser_id' => $order['suid'],
                    'status' => $order['schedule'],
                    'endstatus' => $order['schedule'],
                    'text' => '您有新的售后任务单，请注意跟进',
                ];
                $message[] = [
                    'orderid' => $data['id'],
                    'user_id' =>  $order['suid'],
                    'ouser_id' => $post['suid'],
                    'status' => $order['schedule'],
                    'endstatus' => $order['schedule'],
                    'text' => '此任务单已取消您的售后身份，请留意',
                ];
            }
        } else {
            $post['qkqueren'] = 2;
            $textqk = '新的待指派选址任务单，请注意跟进';
            if ($post['qktype'] == 1) {
                $post['qkqueren'] = 1;
                $textqk = '[无定金]新的待指派选址任务单，请注意跟进';
            }
            $res = $model->strict(false)->insertGetId($post);
            $data['id'] = $res;
            if ($post['suid'] > 0) {
                $message[] = [
                    'orderid' => $data['id'],
                    'user_id' =>  $post['suid'],
                    'ouser_id' => 0,
                    'status' => 1,
                    'endstatus' => 1,
                    'text' => '您有新的售后任务单，请注意跟进',
                ];
            } else {
                //通知售后人员
                $shouhoulist = (new Users())->where(['type' => 9, 'del' => 1])->where("FIND_IN_SET (" . $post['type'] . ",groups)")->select();
                foreach ($shouhoulist as $shouhous) {
                    $message[] = [
                        'orderid' => $data['id'],
                        'user_id' =>  $shouhous['id'],
                        'ouser_id' => 0,
                        'status' => 1,
                        'endstatus' => 1,
                        'text' => '您有新的待指派售后任务单',
                    ];
                }
            }
            $guanli = (new Users())->where(['type' => 4, 'del' => 1])->select();
            foreach ($guanli as $guanlis) {
                $message[] = [
                    'orderid' => $data['id'],
                    'user_id' =>  $guanlis['id'],
                    'ouser_id' => 0,
                    'status' => 1,
                    'endstatus' => 1,
                    'text' => $textqk ?? '',
                ];
            }
        }
        if ($res) {
            if (count($message) > 0) {
                (new Messages())->allowfield(true)->saveAll($message);
            }
            $this->result([], 0, '操作成功');
        }
        $this->result([], 1, '操作失败，请重试');
    }

    //售后经理派单或编辑任务单
    public function addDispatch2()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'typeid' => 'require|gt:0',
            'name' => 'require',
            'mobile' => 'require',
            'yewuid' => 'require|gt:0',
            'address' => 'require',
        ], [
            'typeid.require' => '项目分组不能为空',
            'typeid.gt' => '项目分组不能为空',
            'name.require' => '客户姓名不能为空',
            'mobile.require' => '客户电话不能为空',
            'yewuid.require' => '售后不能为空',
            'yewuid.gt' => '售后不能为空',
            'address.require' => '区域及地址不能为空',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        if (empty($data['mobile'])) {
            $this->result([], 1, '请填写客户手机号');
        }
        if ($this->request->user['type'] != 10 && $this->request->user['type'] != 11) {
            $this->result([], 1, '无此操作权限');
        }
        $yewu = (new Users())->where(['id' => $data['yewuid'], 'del' => 1])->find();
        if (empty($yewu)) {
            $this->result([], 1, '业务经理账号不存在，请重新选择');
        }
        $post = [
            'old' => 2,
            'yuid' => $data['yewuid'],
            'type' => $data['typeid'],
            'name' => $data['name'],
            'phone' =>  $data['mobile'],
            'areas' => $data['address'],
            'xtimes' => $data['xtimes'] ?? '',
            'yremark' => $data['remark'] ?? '',
            'ordertype' => $data['ordertype'] ?? 1,
            'ctype' => $data['ctype'] ?? 1,
        ];
        $message = []; //通知数组
        //为空
        if (empty($data['id'])) {
            $post['user_id'] = $this->request->user_id;
            $post['suid'] = $this->request->user_id;
            $post['schedule'] = 1;
            $post['status'] = 3;
        } else {
            $order = (new Business())->where(['id' => $data['id'], 'suid' => $this->request->user_id])->find();
            if (empty($order)) {
                $this->result([], 1, '任务单不存在或无权限');
            }
            if ($order['schedule'] >= 3) {
                $this->result([], 1, '任务单已确认选址完成，如需修改状态请联系管理员');
            }
        }
        $model = new Business();
        if (!empty($data['id'])) {
            $res = $model->allowfield(true)->save($post, ['id' => $data['id']]);
        } else {
            $res = $model->strict(false)->insertGetId($post);
            $data['id'] = $res;
            $guanli = (new Users())->where(['type' => 4, 'del' => 1])->select();
            foreach ($guanli as $guanlis) {
                $message[] = [
                    'orderid' => $data['id'],
                    'user_id' =>  $guanlis['id'],
                    'ouser_id' => 0,
                    'status' => 1,
                    'endstatus' => 1,
                    'text' => '新的待指派选址任务单，请注意跟进',
                ];
            }
        }
        if ($res) {
            if (count($message) > 0) {
                (new Messages())->allowfield(true)->saveAll($message);
            }
            $this->result([], 0, '操作成功');
        }
        $this->result([], 1, '操作失败，请重试');
    }


    //管理派单或编辑任务单
    public function addDispatch3()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'typeid' => 'require|gt:0',
            'name' => 'require',
            'mobile' => 'require',
            'yewuid' => 'require|gt:0',
            'shouhouid' => 'require|gt:0',
            'kaiyeid' => 'require|gt:0',
            'address' => 'require',
        ], [
            'typeid.require' => '项目分组不能为空',
            'typeid.gt' => '项目分组不能为空',
            'name.require' => '客户姓名不能为空',
            'mobile.require' => '客户电话不能为空',
            'yewuid.require' => '业务经理不能为空',
            'yewuid.gt' => '业务经理不能为空',
            'shouhouid.require' => '售后经理不能为空',
            'shouhouid.gt' => '售后经理不能为空',
            'kaiyeid.require' => '选址督导不能为空',
            'kaiyeid.gt' => '选址督导不能为空',
            'address.require' => '区域及地址不能为空',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        if (empty($data['mobile'])) {
            $this->result([], 1, '请填写客户手机号');
        }
        if ($this->request->user['type'] != 4 && $this->request->user['type'] != 5) {
            $this->result([], 1, '无此操作权限');
        }
        $yewu = (new Users())->where(['id' => $data['yewuid'], 'del' => 1])->find();
        if (empty($yewu)) {
            $this->result([], 1, '业务经理账号不存在，请重新选择');
        }
        $post = [
            'old' => 2,
            'yuid' => $data['yewuid'],
            'duid' => $data['kaiyeid'],
            'suid' => $data['shouhouid'],
            'type' => $data['typeid'],
            'name' => $data['name'],
            'phone' =>  $data['mobile'],
            'areas' => $data['address'],
            'xtimes' => $data['xtimes'] ?? '',
            'yremark' => $data['remark'] ?? '',
            'ordertype' => $data['ordertype'] ?? 1,
            'ctype' => $data['ctype'] ?? 1,
        ];
        $message = []; //通知数组
        //为空
        if (empty($data['id'])) {
            $post['user_id'] = $this->request->user_id;
            $post['schedule'] = 2;
            $post['status'] = 3;
        } else {
            $order = (new Business())->where(['id' => $data['id']])->find();
            if (empty($order)) {
                $this->result([], 1, '任务单不存在或无权限');
            }
            if ($order['schedule'] >= 3) {
                $this->result([], 1, '任务单已确认选址完成，无法更改状态');
            }
        }
        $model = new Business();
        if (!empty($data['id'])) {
            $res = $model->allowfield(true)->save($post, ['id' => $data['id']]);
        } else {
            $res = $model->strict(false)->insertGetId($post);
            $data['id'] = $res;
            $message[] = [
                'orderid' => $data['id'],
                'user_id' =>  $post['duid'],
                'ouser_id' => 0,
                'status' => 2,
                'endstatus' => 2,
                'text' => '您有新的选址任务单，请注意跟进',
            ];
            $message[] = [
                'orderid' => $data['id'],
                'user_id' =>  $post['suid'],
                'ouser_id' => 0,
                'status' => 2,
                'endstatus' => 2,
                'text' => '您有新的选址任务单，请注意跟进',
            ];
        }
        if ($res) {
            if (count($message) > 0) {
                (new Messages())->allowfield(true)->saveAll($message);
            }
            $this->result([], 0, '操作成功');
        }
        $this->result([], 1, '操作失败，请重试');
    }

    public function getzhiding()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'id' => 'require|gt:0'
        ], [
            'id.require' => 'ID不能为空',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        if ($this->request->user['type'] < 4) {
            $this->result([], 1, '无此操作权限');
        }
        $business = (new Business())->where('id', $data['id'])->find();
        if (empty($business)) {
            $this->result([], 1, '任务单不存在');
        }
        $istop = 2;
        if ($business['istop'] == 2) {
            $istop = 1;
        }
        $res = (new Business())->where('id', $data['id'])->update(['istop' => $istop]);
        if ($res) {
            $this->result([], 0, '操作成功');
        }
        $this->result([], 1, '操作失败，请重试');
    }

    //售后提交安装单
    public function addkaioran()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'id' => 'require|gt:0',
            'ordertype' => 'require|in:4,5',
            'name' => 'require',
            'mobile' => 'require|gt:0',
            'reAddress' => 'require',
            'lat' => 'require',
            'lon' => 'require',
            'address' => 'require',
            'ishuo' => 'require|in:2',
            // 'isfirst' => 'require|in:2',
        ], [
            'id.require' => 'ID不能为空',
            'ordertype.require' => '派单类型不能为空',
            'ordertype.in' => '派单类型不正确',
            'name.require' => '客户姓名不能为空',
            'mobile.require' => '客户电话不能为空',
            'reAddress.require' => '定位地址不能为空',
            'lat.gt' => '坐标不能为空',
            'lon.gt' => '坐标不能为空',
            'address.require' => '详细地址不能为空',
            'ishuo.require' => '货架必须填写',
            'ishuo.in' => '货架必须为发货状态',
            'isfirst.require' => '首单必须填写',
            // 'isfirst.in' => '首单必须为发货状态',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        if ($this->request->user['type'] != 10 && $this->request->user['type'] != 11) {
            $this->result([], 1, '无此操作权限');
        }
        if (empty($data['mobile'])) {
            $this->result([], 1, '请填写客户手机号');
        }
        $business = (new Business())->where(['status' => [1, 2, 3], 'id' => $data['id']])->find();
        if (empty($business)) {
            $this->result([], 1, '选中门店已下架');
        }
        //判断就更新
        if ((($business['ordertype'] != 4 && $business['ordertype'] != 5 && $business['ordertype'] != 8) || $business['ordertype'] == $data['ordertype']) && $business['schedule'] <= 4) {
            $post = [
                'old' => 2,
                'luru' => 1,
                'type' => $business['type'],
                'ordertype' => $data['ordertype'],
                'user_id' =>  $this->request->user_id,
                'name' => $data['name'],
                'phone' => $data['mobile'],
                'getaddress' => $data['reAddress'],
                'address' => $data['address'],
                'suid' => $this->request->user_id,
                'images1' => json_encode($data['images1'] ?? [], true),
                'images5' => json_encode($data['images5'] ?? [], true),
                'lat' => $data['lat'],
                'lon' => $data['lon'],
                'status' => 2,
                'schedule' => 4,
                'sremark' => $data['remark'] ?? '',
                'created' => date('Y-m-d H:i:s'),
            ];
            if (!empty($data['zhuangxiu'])) {
                $post['zhuangxiu'] = $data['zhuangxiu'];
            }
            if (!empty($data['ishuo'])) {
                $post['ishuo'] = $data['ishuo'];
            }
            if (!empty($data['isfirst'])) {
                $post['isfirst'] = $data['isfirst'];
                if ($data['isfirst'] == 2 && !empty($data['firsttimes'])) {
                    $post['firsttimes'] = $data['firsttimes'];
                }
                if ($data['isfirst'] == 2 && empty($data['firsttimes'])) {
                    $this->result([], 1, '首单发货日期必须填写');
                }
            }
            if (!empty($data['weikuan'])) {
                $post['weikuan'] = $data['weikuan'];
            }

            //查看
            $url = 'https://apis.map.qq.com/ws/geocoder/v1';
            try {
                $result = api_curl($url, ['location' => $data['lat'] . ',' . $data['lon'], 'key' => 'KHMBZ-ADFKZ-H2IXE-TUFHJ-RR4LV-N7F4D', 'poi_options' => 'radius=50;policy=5']);
                $post['province'] = $result['result']['ad_info']['province'] ?? '';
                $post['city'] = $result['result']['ad_info']['city'] ?? '';
                $post['area'] = $result['result']['ad_info']['district'] ?? '';
            } catch (\Exception $e) {
                $this->result([], 1, $e->getMessage());
            }
            $guanli = (new Users())->where(['type' => 5, 'del' => 1])->select();
            foreach ($guanli as $guanlis) {
                $message[] = [
                    'orderid' => $data['id'],
                    'user_id' =>  $guanlis['id'],
                    'ouser_id' => 0,
                    'status' => 3,
                    'endstatus' => 4,
                    'text' => '售后人员已提交开业派单，请查看信息并派单',
                ];
            }
            $model = new Business();
            $res = $model->allowfield(true)->save($post, ['id' => $data['id']]);
            if ($res) {
                if (count($message) > 0) {
                    (new Messages())->allowfield(true)->saveAll($message);
                }
                $this->result([], 0, '提交成功');
            }
            $this->result([], 1, '提交失败，请重试');
        } else {
            //查询子任务单是否存在
            $sons = (new Business())->where(['topid' => $data['id'], 'schedule' => [1, 2, 3, 4, 5, 6], 'ordertype' => $data['ordertype']])->find();
            if (empty($sons)) {
                unset($business['id']);
                $post = $business;
                $post = [
                    'old' => 2,
                    'luru' => 1,
                    'type' => $business['type'],
                    'topid' => $data['id'],
                    'ctype' => 2,
                    'ordertype' => $data['ordertype'],
                    'user_id' =>  $this->request->user_id,
                    'name' => $data['name'],
                    'phone' => $data['mobile'],
                    'getaddress' => $data['reAddress'],
                    'address' => $data['address'],
                    'suid' => $this->request->user_id,
                    'images1' => json_encode($data['images1'] ?? [], true),
                    'images5' => json_encode($data['images5'] ?? [], true),
                    'lat' => $data['lat'],
                    'lon' => $data['lon'],
                    'status' => 2,
                    'schedule' => 4,
                    'sremark' => $data['remark'] ?? '',
                    'created' => date('Y-m-d H:i:s')
                ];
                if (!empty($data['zhuangxiu'])) {
                    $post['zhuangxiu'] = $data['zhuangxiu'];
                }
                if (!empty($data['ishuo'])) {
                    $post['ishuo'] = $data['ishuo'];
                }
                if (!empty($data['isfirst'])) {
                    $post['isfirst'] = $data['isfirst'];
                    if ($data['isfirst'] == 2 && !empty($data['firsttimes'])) {
                        $post['firsttimes'] = $data['firsttimes'];
                    }
                    if ($data['isfirst'] == 2 && empty($data['firsttimes'])) {
                        $this->result([], 1, '首单发货日期必须填写');
                    }
                }
                if (!empty($data['weikuan'])) {
                    $post['weikuan'] = $data['weikuan'];
                }
                //查看
                $url = 'https://apis.map.qq.com/ws/geocoder/v1';
                try {
                    $result = api_curl($url, ['location' => $data['lat'] . ',' . $data['lon'], 'key' => 'KHMBZ-ADFKZ-H2IXE-TUFHJ-RR4LV-N7F4D', 'poi_options' => 'radius=50;policy=5']);
                    $post['province'] = $result['result']['ad_info']['province'] ?? '';
                    $post['city'] = $result['result']['ad_info']['city'] ?? '';
                    $post['area'] = $result['result']['ad_info']['district'] ?? '';
                } catch (\Exception $e) {
                    $this->result([], 1, $e->getMessage());
                }
                $guanli = (new Users())->where(['type' => 5, 'del' => 1])->select();
                $model = new Business();
                $sons['id'] = $model->strict(false)->insertGetId($post);
                if ($sons['id']) {
                    foreach ($guanli as $guanlis) {
                        $message[] = [
                            'orderid' => $sons['id'],
                            'user_id' =>  $guanlis['id'],
                            'ouser_id' => 0,
                            'status' => 3,
                            'endstatus' => 4,
                            'text' => '售后人员已提交开业派单，请查看信息并派单',
                        ];
                    }
                    if (count($message) > 0) {
                        (new Messages())->allowfield(true)->saveAll($message);
                    }
                    $this->result([], 0, '提交成功');
                }
                $this->result([], 1, '提交失败，请重试');
            } else {
                $post = [
                    'old' => 2,
                    'luru' => 1,
                    'type' => $business['type'],
                    'topid' => $data['id'],
                    'ctype' => 2,
                    'ordertype' => $data['ordertype'],
                    'user_id' =>  $this->request->user_id,
                    'images1' => json_encode($data['images1'] ?? [], true),
                    'images5' => json_encode($data['images5'] ?? [], true),
                    'name' => $data['name'],
                    'phone' => $data['mobile'],
                    'getaddress' => $data['reAddress'],
                    'address' => $data['address'],
                    'suid' => $this->request->user_id,
                    'lat' => $data['lat'],
                    'lon' => $data['lon'],
                    'status' => $sons['status'],
                    'schedule' => $sons['schedule'],
                    'sremark' => $data['remark'] ?? '',
                    'created' => date('Y-m-d H:i:s')
                ];
                if (!empty($data['zhuangxiu'])) {
                    $post['zhuangxiu'] = $data['zhuangxiu'];
                }
                if (!empty($data['ishuo'])) {
                    $post['ishuo'] = $data['ishuo'];
                }
                if (!empty($data['isfirst'])) {
                    $post['isfirst'] = $data['isfirst'];
                    if ($data['isfirst'] == 2 && !empty($data['firsttimes'])) {
                        $post['firsttimes'] = $data['firsttimes'];
                    }
                    if ($data['isfirst'] == 2 && empty($data['firsttimes'])) {
                        $this->result([], 1, '首单发货日期必须填写');
                    }
                }
                if (!empty($data['weikuan'])) {
                    $post['weikuan'] = $data['weikuan'];
                }
                //查看
                $url = 'https://apis.map.qq.com/ws/geocoder/v1';
                try {
                    $result = api_curl($url, ['location' => $data['lat'] . ',' . $data['lon'], 'key' => 'KHMBZ-ADFKZ-H2IXE-TUFHJ-RR4LV-N7F4D', 'poi_options' => 'radius=50;policy=5']);
                    $post['province'] = $result['result']['ad_info']['province'] ?? '';
                    $post['city'] = $result['result']['ad_info']['city'] ?? '';
                    $post['area'] = $result['result']['ad_info']['district'] ?? '';
                } catch (\Exception $e) {
                    $this->result([], 1, $e->getMessage());
                }
                $guanli = (new Users())->where(['type' => 5, 'del' => 1])->select();
                foreach ($guanli as $guanlis) {
                    $message[] = [
                        'orderid' => $sons['id'],
                        'user_id' =>  $guanlis['id'],
                        'ouser_id' => 0,
                        'status' => 3,
                        'endstatus' => 4,
                        'text' => '售后人员已提交开业派单，请查看信息并派单',
                    ];
                }
                $model = new Business();
                $res = $model->allowfield(true)->save($post, ['id' => $sons['id']]);
                if ($res) {
                    if (count($message) > 0) {
                        (new Messages())->allowfield(true)->saveAll($message);
                    }
                    $this->result([], 0, '提交成功');
                }
                $this->result([], 1, '提交失败，请重试');
            }
        }
    }

    //售后提交巡店回收 二次开业单
    public function addxunorhui()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'id' => 'require|gt:0',
            'ordertype' => 'require|in:6,7,8',
            'name' => 'require',
            'mobile' => 'require|gt:0',
            'reAddress' => 'require',
            'lat' => 'require',
            'lon' => 'require',
            'address' => 'require',
        ], [
            'id.require' => 'ID不能为空',
            'ordertype.require' => '派单类型不能为空',
            'ordertype.in' => '派单类型不正确',
            'name.require' => '客户姓名不能为空',
            'mobile.require' => '客户电话不能为空',
            'reAddress.require' => '定位地址不能为空',
            'lat.gt' => '坐标不能为空',
            'lon.gt' => '坐标不能为空',
            'address.require' => '详细地址不能为空',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        if (empty($data['mobile'])) {
            $this->result([], 1, '请填写客户手机号');
        }
        if ($this->request->user['type'] != 10 && $this->request->user['type'] != 11) {
            $this->result([], 1, '无此操作权限');
        }
        $business = (new Business())->where(['status' => [1, 2, 3], 'id' => $data['id']])->find();
        if (empty($business)) {
            $this->result([], 1, '选中门店已下架');
        }
        //查询进行中子任务单是否存在
        $sons = (new Business())->where(['topid' => $data['id'], 'status' => [1, 2, 3, 4, 5, 6], 'ordertype' => $data['ordertype']])->find();
        if (empty($sons)) {
            unset($business['id']);
            $post = $business;
            $post = [
                'old' => 2,
                'luru' => 1,
                'topid' => $data['id'],
                'type' => $business['type'],
                'ctype' => 2,
                'ordertype' => $data['ordertype'],
                'user_id' =>  $this->request->user_id,
                'name' => $data['name'],
                'phone' => $data['mobile'],
                'getaddress' => $data['reAddress'],
                'address' => $data['address'],
                'suid' => $this->request->user_id,
                'lat' => $data['lat'],
                'lon' => $data['lon'],
                'status' => 2,
                'schedule' => 4,
                'sremark' => $data['remark'] ?? '',
                'created' => date('Y-m-d H:i:s')
            ];
            //查看
            $url = 'https://apis.map.qq.com/ws/geocoder/v1';
            try {
                $result = api_curl($url, ['location' => $data['lat'] . ',' . $data['lon'], 'key' => 'KHMBZ-ADFKZ-H2IXE-TUFHJ-RR4LV-N7F4D', 'poi_options' => 'radius=50;policy=5']);
                $post['province'] = $result['result']['ad_info']['province'] ?? '';
                $post['city'] = $result['result']['ad_info']['city'] ?? '';
                $post['area'] = $result['result']['ad_info']['district'] ?? '';
            } catch (\Exception $e) {
                $this->result([], 1, $e->getMessage());
            }
            $guanli = (new Users())->where(['type' => 5, 'del' => 1])->select();
            $model = new Business();
            $sons['id'] = $model->strict(false)->insertGetId($post);
            if ($sons['id']) {
                foreach ($guanli as $guanlis) {
                    $message[] = [
                        'orderid' => $sons['id'],
                        'user_id' =>  $guanlis['id'],
                        'ouser_id' => 0,
                        'status' => 3,
                        'endstatus' => 4,
                        'text' => '售后人员已提交巡店或回收派单，请查看信息并派单',
                    ];
                }
                if (count($message) > 0) {
                    (new Messages())->allowfield(true)->saveAll($message);
                }
                $this->result([], 0, '提交成功');
            }
            $this->result([], 1, '提交失败，请重试');
        } else {
            $post = [
                'old' => 2,
                'luru' => 1,
                'type' => $business['type'],
                'topid' => $data['id'],
                'ctype' => 2,
                'ordertype' => $data['ordertype'],
                'user_id' =>  $this->request->user_id,
                'name' => $data['name'],
                'phone' => $data['mobile'],
                'getaddress' => $data['reAddress'],
                'address' => $data['address'],
                'suid' => $this->request->user_id,
                'lat' => $data['lat'],
                'lon' => $data['lon'],
                'status' => 2,
                'schedule' => 4,
                'sremark' => $data['remark'] ?? '',
                'created' => date('Y-m-d H:i:s')
            ];
            //查看
            $url = 'https://apis.map.qq.com/ws/geocoder/v1';
            try {
                $result = api_curl($url, ['location' => $data['lat'] . ',' . $data['lon'], 'key' => 'KHMBZ-ADFKZ-H2IXE-TUFHJ-RR4LV-N7F4D', 'poi_options' => 'radius=50;policy=5']);
                $post['province'] = $result['result']['ad_info']['province'] ?? '';
                $post['city'] = $result['result']['ad_info']['city'] ?? '';
                $post['area'] = $result['result']['ad_info']['district'] ?? '';
            } catch (\Exception $e) {
                $this->result([], 1, $e->getMessage());
            }
            $guanli = (new Users())->where(['type' => 5, 'del' => 1])->select();
            foreach ($guanli as $guanlis) {
                $message[] = [
                    'orderid' => $sons['id'],
                    'user_id' =>  $guanlis['id'],
                    'ouser_id' => 0,
                    'status' => 3,
                    'endstatus' => 4,
                    'text' => '售后人员已提交巡店或回收派单，请查看信息并派单',
                ];
            }
            $model = new Business();
            $res = $model->allowfield(true)->save($post, ['id' => $sons['id']]);
            if ($res) {
                if (count($message) > 0) {
                    (new Messages())->allowfield(true)->saveAll($message);
                }
                $this->result([], 0, '提交成功');
            }
            $this->result([], 1, '提交失败，请重试');
        }
    }


    //派单员提交安装单
    public function addkaioran2()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'id' => 'require|gt:0',
            'ordertype' => 'require|in:4,5',
            'name' => 'require',
            'mobile' => 'require|gt:0',
            'reAddress' => 'require',
            'lat' => 'require',
            'lon' => 'require',
            'address' => 'require',
            'shouhouid' => 'require',
            'kaiyeid' => 'require',
            'times' => 'require',
        ], [
            'id.require' => 'ID不能为空',
            'ordertype.require' => '派单类型不能为空',
            'ordertype.in' => '派单类型不正确',
            'name.require' => '客户姓名不能为空',
            'mobile.require' => '客户电话不能为空',
            'reAddress.require' => '定位地址不能为空',
            'lat.gt' => '坐标不能为空',
            'lon.gt' => '坐标不能为空',
            'address.require' => '详细地址不能为空',
            'shouhouid.require' => '售后不能为空',
            'kaiyeid.require' => '督导不能为空',
            'times.require' => '督导出发时间不能为空',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        if (empty($data['mobile'])) {
            $this->result([], 1, '请填写客户手机号');
        }
        if ($this->request->user['type'] != 4 && $this->request->user['type'] != 5) {
            $this->result([], 1, '无此操作权限');
        }
        $business = (new Business())->where(['status' => [1, 2, 3], 'id' => $data['id']])->find();
        if (empty($business)) {
            $this->result([], 1, '选中门店已下架');
        }
        //判断就更新
        if ((($business['ordertype'] != 4 && $business['ordertype'] != 5) || $business['ordertype'] == $data['ordertype']) && $business['schedule'] <= 4) {
            $post = [
                'old' => 2,
                'type' => $business['type'],
                'ordertype' => $data['ordertype'],
                'user_id' =>  $this->request->user_id,
                'name' => $data['name'],
                'phone' => $data['mobile'],
                'getaddress' => $data['reAddress'],
                'address' => $data['address'],
                'suid' => $data['shouhouid'],
                'kuid' => $data['kaiyeid'],
                'kdates' => $data['times'],
                'lat' => $data['lat'],
                'lon' => $data['lon'],
                'status' => 2,
                'schedule' => 5,
                'ycreated' => date('Y-m-d H:i:s'),
                'images1' => json_encode($data['images1'] ?? [], true),
                'images5' => json_encode($data['images5'] ?? [], true),
                'sremark' => $data['remark'] ?? '',
                'created' => date('Y-m-d H:i:s')
            ];
            if (!empty($data['zhuangxiu'])) {
                $post['zhuangxiu'] = $data['zhuangxiu'];
            }
            if (!empty($data['ishuo'])) {
                $post['ishuo'] = $data['ishuo'];
            }
            if (!empty($data['isfirst'])) {
                $post['isfirst'] = $data['isfirst'];
                if ($data['isfirst'] == 2 && !empty($data['firsttimes'])) {
                    $post['firsttimes'] = $data['firsttimes'];
                }
                if ($data['isfirst'] == 2 && empty($data['firsttimes'])) {
                    $this->result([], 1, '首单发货日期必须填写');
                }
            }
            if (!empty($data['weikuan'])) {
                $post['weikuan'] = $data['weikuan'];
            }
            //查看
            $url = 'https://apis.map.qq.com/ws/geocoder/v1';
            try {
                $result = api_curl($url, ['location' => $data['lat'] . ',' . $data['lon'], 'key' => 'KHMBZ-ADFKZ-H2IXE-TUFHJ-RR4LV-N7F4D', 'poi_options' => 'radius=50;policy=5']);
                $post['province'] = $result['result']['ad_info']['province'] ?? '';
                $post['city'] = $result['result']['ad_info']['city'] ?? '';
                $post['area'] = $result['result']['ad_info']['district'] ?? '';
            } catch (\Exception $e) {
                $this->result([], 1, $e->getMessage());
            }
            $message[] = [
                'orderid' => $data['id'],
                'user_id' =>  $data['kaiyeid'],
                'ouser_id' => 0,
                'status' => 5,
                'endstatus' => 5,
                'text' => '您有新的派单，请查看留意',
            ];
            $model = new Business();
            $res = $model->allowfield(true)->save($post, ['id' => $data['id']]);
            if ($res) {
                if (count($message) > 0) {
                    (new Messages())->allowfield(true)->saveAll($message);
                }
                $this->result([], 0, '提交成功');
            }
            $this->result([], 1, '提交失败，请重试');
        } else {
            //查询子任务单是否存在
            $sons = (new Business())->where(['topid' => $data['id'], 'schedule' => [1, 2, 3, 4, 5, 6], 'ordertype' => $data['ordertype']])->find();
            if (empty($sons)) {
                unset($business['id']);
                $post = $business;
                $post = [
                    'old' => 2,
                    'luru' => 1,
                    'type' => $business['type'],
                    'topid' => $data['id'],
                    'ctype' => 2,
                    'ordertype' => $data['ordertype'],
                    'user_id' =>  $this->request->user_id,
                    'name' => $data['name'],
                    'phone' => $data['mobile'],
                    'getaddress' => $data['reAddress'],
                    'address' => $data['address'],
                    'suid' => $data['shouhouid'],
                    'kuid' => $data['kaiyeid'],
                    'kdates' => $data['times'],
                    'lat' => $data['lat'],
                    'lon' => $data['lon'],
                    'status' => 2,
                    'schedule' => 5,
                    'images1' => json_encode($data['images1'] ?? [], true),
                    'images5' => json_encode($data['images5'] ?? [], true),
                    'ycreated' => date('Y-m-d H:i:s'),
                    'sremark' => $data['remark'] ?? '',
                    'created' => date('Y-m-d H:i:s')
                ];
                if (!empty($data['zhuangxiu'])) {
                    $post['zhuangxiu'] = $data['zhuangxiu'];
                }
                if (!empty($data['ishuo'])) {
                    $post['ishuo'] = $data['ishuo'];
                }
                if (!empty($data['isfirst'])) {
                    $post['isfirst'] = $data['isfirst'];
                    if ($data['isfirst'] == 2 && !empty($data['firsttimes'])) {
                        $post['firsttimes'] = $data['firsttimes'];
                    }
                    if ($data['isfirst'] == 2 && empty($data['firsttimes'])) {
                        $this->result([], 1, '首单发货日期必须填写');
                    }
                }
                if (!empty($data['weikuan'])) {
                    $post['weikuan'] = $data['weikuan'];
                }
                //查看
                $url = 'https://apis.map.qq.com/ws/geocoder/v1';
                try {
                    $result = api_curl($url, ['location' => $data['lat'] . ',' . $data['lon'], 'key' => 'KHMBZ-ADFKZ-H2IXE-TUFHJ-RR4LV-N7F4D', 'poi_options' => 'radius=50;policy=5']);
                    $post['province'] = $result['result']['ad_info']['province'] ?? '';
                    $post['city'] = $result['result']['ad_info']['city'] ?? '';
                    $post['area'] = $result['result']['ad_info']['district'] ?? '';
                } catch (\Exception $e) {
                    $this->result([], 1, $e->getMessage());
                }
                $model = new Business();
                $sons['id'] = $model->strict(false)->insertGetId($post);
                if ($sons['id']) {
                    $message[] = [
                        'orderid' => $sons['id'],
                        'user_id' =>  $data['kaiyeid'],
                        'ouser_id' => 0,
                        'status' => 5,
                        'endstatus' => 5,
                        'text' => '您有新的派单，请查看留意',
                    ];
                    if (count($message) > 0) {
                        (new Messages())->allowfield(true)->saveAll($message);
                    }
                    $this->result([], 0, '提交成功');
                }
                $this->result([], 1, '提交失败，请重试');
            } else {
                $post = [
                    'old' => 2,
                    'luru' => 1,
                    'type' => $business['type'],
                    'topid' => $data['id'],
                    'ctype' => 2,
                    'ordertype' => $data['ordertype'],
                    'user_id' =>  $this->request->user_id,
                    'name' => $data['name'],
                    'phone' => $data['mobile'],
                    'getaddress' => $data['reAddress'],
                    'address' => $data['address'],
                    'suid' => $data['shouhouid'],
                    'kuid' => $data['kaiyeid'],
                    'kdates' => $data['times'],
                    'lat' => $data['lat'],
                    'lon' => $data['lon'],
                    'images1' => json_encode($data['images1'] ?? [], true),
                    'images5' => json_encode($data['images5'] ?? [], true),
                    'status' => $sons['status'],
                    'schedule' => $sons['schedule'],
                    'sremark' => $data['remark'] ?? '',
                    'ycreated' => date('Y-m-d H:i:s'),
                    'created' => date('Y-m-d H:i:s')
                ];
                if (!empty($data['zhuangxiu'])) {
                    $post['zhuangxiu'] = $data['zhuangxiu'];
                }
                if (!empty($data['ishuo'])) {
                    $post['ishuo'] = $data['ishuo'];
                }
                if (!empty($data['isfirst'])) {
                    $post['isfirst'] = $data['isfirst'];
                    if ($data['isfirst'] == 2 && !empty($data['firsttimes'])) {
                        $post['firsttimes'] = $data['firsttimes'];
                    }
                    if ($data['isfirst'] == 2 && empty($data['firsttimes'])) {
                        $this->result([], 1, '首单发货日期必须填写');
                    }
                }
                if (!empty($data['weikuan'])) {
                    $post['weikuan'] = $data['weikuan'];
                }
                //查看
                $url = 'https://apis.map.qq.com/ws/geocoder/v1';
                try {
                    $result = api_curl($url, ['location' => $data['lat'] . ',' . $data['lon'], 'key' => 'KHMBZ-ADFKZ-H2IXE-TUFHJ-RR4LV-N7F4D', 'poi_options' => 'radius=50;policy=5']);
                    $post['province'] = $result['result']['ad_info']['province'] ?? '';
                    $post['city'] = $result['result']['ad_info']['city'] ?? '';
                    $post['area'] = $result['result']['ad_info']['district'] ?? '';
                } catch (\Exception $e) {
                    $this->result([], 1, $e->getMessage());
                }
                $message[] = [
                    'orderid' => $sons['id'],
                    'user_id' =>  $data['kaiyeid'],
                    'ouser_id' => 0,
                    'status' => 5,
                    'endstatus' => 5,
                    'text' => '您有新的派单，请查看留意',
                ];
                $model = new Business();
                $res = $model->allowfield(true)->save($post, ['id' => $sons['id']]);
                if ($res) {
                    if (count($message) > 0) {
                        (new Messages())->allowfield(true)->saveAll($message);
                    }
                    $this->result([], 0, '提交成功');
                }
                $this->result([], 1, '提交失败，请重试');
            }
        }
    }

    //派单员提交巡店回收 二次开业单
    public function addxunorhui2()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'id' => 'require|gt:0',
            'ordertype' => 'require|in:6,7,8',
            'name' => 'require',
            'mobile' => 'require|gt:0',
            'reAddress' => 'require',
            'lat' => 'require',
            'lon' => 'require',
            'address' => 'require',
            'shouhouid' => 'require',
            'kaiyeid' => 'require',
            'times' => 'require',
        ], [
            'id.require' => 'ID不能为空',
            'ordertype.require' => '派单类型不能为空',
            'ordertype.in' => '派单类型不正确',
            'name.require' => '客户姓名不能为空',
            'mobile.require' => '客户电话不能为空',
            'reAddress.require' => '定位地址不能为空',
            'lat.gt' => '坐标不能为空',
            'lon.gt' => '坐标不能为空',
            'address.require' => '详细地址不能为空',
            'shouhouid.require' => '售后人员不能为空',
            'kaiyeid.require' => '督导人员不能为空',
            'times.require' => '督导出发时间不能为空',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        if (empty($data['mobile'])) {
            $this->result([], 1, '请填写客户手机号');
        }
        if ($this->request->user['type'] != 4 && $this->request->user['type'] != 5) {
            $this->result([], 1, '无此操作权限');
        }
        $business = (new Business())->where(['status' => [1, 2, 3], 'id' => $data['id']])->find();
        if (empty($business)) {
            $this->result([], 1, '选中门店已下架');
        }
        //查询进行中子任务单是否存在
        $sons = (new Business())->where(['topid' => $data['id'], 'status' => [1, 2, 3, 4, 5, 6], 'ordertype' => $data['ordertype']])->find();
        if (empty($sons)) {
            unset($business['id']);
            $post = $business;
            $post = [
                'old' => 2,
                'luru' => 1,
                'topid' => $data['id'],
                'type' => $business['type'],
                'ctype' => 2,
                'ordertype' => $data['ordertype'],
                'user_id' =>  $this->request->user_id,
                'name' => $data['name'],
                'phone' => $data['mobile'],
                'getaddress' => $data['reAddress'],
                'address' => $data['address'],
                'suid' => $data['shouhouid'],
                'kuid' => $data['kaiyeid'],
                'kdates' => $data['times'],
                'lat' => $data['lat'],
                'lon' => $data['lon'],
                'status' => 2,
                'schedule' => 5,
                'sremark' => $data['remark'] ?? '',
                'ycreated' => date('Y-m-d H:i:s'),
                'created' => date('Y-m-d H:i:s')
            ];
            //查看
            $url = 'https://apis.map.qq.com/ws/geocoder/v1';
            try {
                $result = api_curl($url, ['location' => $data['lat'] . ',' . $data['lon'], 'key' => 'KHMBZ-ADFKZ-H2IXE-TUFHJ-RR4LV-N7F4D', 'poi_options' => 'radius=50;policy=5']);
                $post['province'] = $result['result']['ad_info']['province'] ?? '';
                $post['city'] = $result['result']['ad_info']['city'] ?? '';
                $post['area'] = $result['result']['ad_info']['district'] ?? '';
            } catch (\Exception $e) {
                $this->result([], 1, $e->getMessage());
            }
            $model = new Business();
            $sons['id'] = $model->strict(false)->insertGetId($post);
            if ($sons['id']) {
                $message[] = [
                    'orderid' => $sons['id'],
                    'user_id' =>  $data['kaiyeid'],
                    'ouser_id' => 0,
                    'status' => 5,
                    'endstatus' => 5,
                    'text' => '你有新的派单，请查看信息',
                ];
                if (count($message) > 0) {
                    (new Messages())->allowfield(true)->saveAll($message);
                }
                $this->result([], 0, '提交成功');
            }
            $this->result([], 1, '提交失败，请重试');
        } else {
            $post = [
                'old' => 2,
                'luru' => 1,
                'type' => $business['type'],
                'topid' => $data['id'],
                'ctype' => 2,
                'ordertype' => $data['ordertype'],
                'user_id' =>  $this->request->user_id,
                'name' => $data['name'],
                'phone' => $data['mobile'],
                'getaddress' => $data['reAddress'],
                'address' => $data['address'],
                'suid' => $data['shouhouid'],
                'kuid' => $data['kaiyeid'],
                'kdates' => $data['times'],
                'lat' => $data['lat'],
                'lon' => $data['lon'],
                'status' => 2,
                'schedule' => 5,
                'ycreated' => date('Y-m-d H:i:s'),
                'sremark' => $data['remark'] ?? '',
                'created' => date('Y-m-d H:i:s')
            ];
            //查看
            $url = 'https://apis.map.qq.com/ws/geocoder/v1';
            try {
                $result = api_curl($url, ['location' => $data['lat'] . ',' . $data['lon'], 'key' => 'KHMBZ-ADFKZ-H2IXE-TUFHJ-RR4LV-N7F4D', 'poi_options' => 'radius=50;policy=5']);
                $post['province'] = $result['result']['ad_info']['province'] ?? '';
                $post['city'] = $result['result']['ad_info']['city'] ?? '';
                $post['area'] = $result['result']['ad_info']['district'] ?? '';
            } catch (\Exception $e) {
                $this->result([], 1, $e->getMessage());
            }
            $message[] = [
                'orderid' => $sons['id'],
                'user_id' =>  $data['kaiyeid'],
                'ouser_id' => 0,
                'status' => 5,
                'endstatus' => 5,
                'text' => '你有新的派单，请查看信息',
            ];
            $model = new Business();
            $res = $model->allowfield(true)->save($post, ['id' => $sons['id']]);
            if ($res) {
                if (count($message) > 0) {
                    (new Messages())->allowfield(true)->saveAll($message);
                }
                $this->result([], 0, '提交成功');
            }
            $this->result([], 1, '提交失败，请重试');
        }
    }

    //考勤打卡
    public function kaoqin()
    {
        if ($this->request->isGet()) {
            $lon  = $this->request->get('lng/f', '0');
            $lat  = $this->request->get('lat/f', '0');
            //附近闭店查询商家
            $filed = 'ROUND(6378.138*2*ASIN(SQRT(POW(SIN((' . $lat . '*PI()/180-lat*PI()/180)/2),2)+COS(' . $lat . '*PI()/180)*COS(lat*PI()/180)*POW(SIN((' . $lon . '*PI()/180-lon*PI()/180)/2),2)))*100)/100 AS dist';
            $chaxun = (new Business())
                ->field('id,' . $filed)
                ->having('dist <= 30')
                ->where('ctype', 1)->where(['schedule' => [5, 6, 7], 'status' => [1, 2, 3, 4], 'bicloses' => [2]])->where('lat|lon', ">", 0)->where('type', "not in", [1, 2])->select();
            $chaxunbus = count($chaxun);
            //获取今日
            $ymd = date('Ymd');
            //判断今日是否打卡
            $sign = (new Sign())->where(['user_id' => $this->request->user_id, 'yearday' => $ymd])->find();
            //上下班时间
            $signtime = (new Config())->where('name', 'signtime')->value('value') ?? '';
            $signtime = json_decode($signtime, true) ?? [];
            //地点坐标
            $signaddress = (new Config())->where('name', 'signaddress')->value('value') ?? '';
            $signaddress = json_decode($signaddress, true) ?? [];
            //距离接受
            $signrange = (new Config())->where('name', 'signrange')->value('value') ?? 0.1;
            $signrange = (float)$signrange;
            $wai = 2;
            foreach ($signaddress as $address) {
                $latlng = explode(',', $address['latlng']) ?? [];
                if (count($latlng) == 2 && $wai == 2) {
                    $km = getDistance($lon, $lat, $latlng[0], $latlng[1]);
                    if ($km <= $signrange) {
                        $wai = 1;
                    }
                }
            }
            if (empty($sign) || empty($sign['monstar']) || $sign['monstar'] != 2) {
                $signlog = (new Signlog())->where(['user_id' => $this->request->user_id, 'yearday' => $ymd, 'monoraft' => 1, 'status' => 1])->find();
                if (!empty($signlog)) {
                    $sign['monstar'] = 4;
                }
            }
            if (empty($sign) || empty($sign['aftstar']) || $sign['aftstar'] != 2) {
                $signlog = (new Signlog())->where(['user_id' => $this->request->user_id, 'yearday' => $ymd, 'monoraft' => 2, 'status' => 1])->find();
                if (!empty($signlog)) {
                    $sign['aftstar'] = 4;
                }
            }
            $result = [
                'mon' => $signtime['mon'] ?? '',
                'aft' => $signtime['aft'] ?? '',
                'month' => $sign['monstar'] ?? 1, //早城是否打卡 1未打卡 2打卡
                'after' => $sign['aftstar'] ?? 1, //晚上是否打卡 1未打卡 2打卡
                'month_time' => !empty($sign['month_time']) ? date('H:i', strtotime($sign['month_time'])) : '', //早上打卡时间
                'after_time' => !empty($sign['after_time']) ? date('H:i', strtotime($sign['after_time'])) : '', //晚上打卡时间
                'iswai' => $wai ?? 2, //1内勤 2外勤
                'isbiclose' => $chaxunbus,
                'guize' => ['请等待定位成功后打卡，如果获取不到定位信息，请确认是否打开手机GPS开关，已经微信小程序位置授权。']
            ];
            $this->result($result, 0, '获取成功');
        } else {
            //获取本月
            $data  = $this->request->post();
            $userid = $this->request->post('userid/d', $this->request->user_id);
            if (empty($data['yearmonth'])) {
                $ymd = date('Ym');
            } else {
                $ymd = $data['yearmonth'];
            }
            if ($ymd == date('Ym')) {
                $days = date('d') - 1;
            } elseif ($ymd < date('Ym')) {
                $year = substr($ymd, 0, 4);
                $month = substr($ymd, 4, 2);
                $date = $year . '-' . $month . '-01'; // 假设是月初的时间戳
                $days = date('t', strtotime($date));
            } else {
                $days = 0;
            }
            $result = [];
            $jiaqi = 0;
            for ($i = 1; $i <= $days; $i++) {
                if ($i < 10) {
                    $i = '0' . $i;
                }
                $years = $ymd . $i;
                //查找是否请假
                $newday = date('Y-m-d', strtotime($years));
                $leave = (new Leave())->order('created desc')->where(['user_id' => $userid, 'status' => 2])->whereTime('startime', '<=', $newday)
                    ->whereTime('endtime', '>=', $newday)->find();
                $sign = (new Sign())->field('yearday,monstar,aftstar,monwei,afterwei')->where(['user_id' => $userid, 'yearday' => $years])->find();
                $text = '';
                if (!empty($leave)) {
                    if ($leave['type'] == 2) {
                        $jiaqi += 1;
                        $text = '假/假';
                    }
                    if ($leave['type'] == 1) {
                        if ($leave['startime'] == $newday || $leave['endtime'] == $newday) {
                            $jiaqi += 0.5;
                        } else {
                            $jiaqi += 1;
                        }
                        if (($leave['startime'] == $newday && $leave['startype'] == 1) || $leave['startime'] != $newday) {
                            $text = '假';
                        }
                        if ($leave['startime'] == $newday && $leave['startype'] == 2) {
                            if (empty($sign)) {
                                $text = '缺卡';
                            } elseif ($sign['monstar'] == 1) {
                                $text = '缺早';
                            } elseif ($sign['monstar'] == 3) {
                                $text = '迟到';
                            }
                        }
                        if (($leave['endtime'] == $newday && $leave['endtype'] == 2) || $leave['endtime'] != $newday) {
                            $text .= '/假';
                        }
                        if ($leave['endtime'] == $newday && $leave['endtype'] == 1) {
                            if (empty($sign)) {
                                if (empty($text)) {
                                    $text = '缺卡';
                                } else {
                                    $text .= '/缺卡';
                                }
                            }
                            if ($sign['aftstar'] == 1) {
                                if (empty($text)) {
                                    $text = '缺晚';
                                } elseif ($years != date('Ymd')) {
                                    $text .= '/缺晚';
                                }
                            } elseif ($sign['aftstar'] == 3) {
                                if (empty($text)) {
                                    $text = '早退';
                                } else {
                                    $text .= '/早退';
                                }
                            }
                        }
                    }
                } elseif (empty($sign)) {
                    $text = '旷工';
                } else {
                    if ($sign['monwei'] == 2) {
                        $text = '违规';
                    } elseif ($sign['monstar'] == 1) {
                        $text = '缺早';
                    } elseif ($sign['monstar'] == 3) {
                        $text = '迟到';
                    }
                    if ($sign['afterwei'] == 2) {
                        if (empty($text)) {
                            $text = '违规';
                        } elseif ($years != date('Ymd')) {
                            $text .= '/违规';
                        }
                    } elseif ($sign['aftstar'] == 1) {
                        if (empty($text)) {
                            $text = '缺晚';
                        } elseif ($years != date('Ymd')) {
                            $text .= '/缺晚';
                        }
                    } elseif ($sign['aftstar'] == 3) {
                        if (empty($text)) {
                            $text = '早退';
                        } else {
                            $text .= '/早退';
                        }
                    }
                }
                if (!empty($text)) {
                    $result[] = [
                        'date' => date('Y-m-d', strtotime($years)),
                        'info' => $text,
                    ];
                }
            }
            $this->result($result, 0, '获取成功');
        }
    }

    public function postsqkaoqin()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'lat' => 'require|gt:0',
            'lng' => 'require|gt:0',
            'address' => 'require',
            'iswai' => 'require',
            'date' => 'require',
            'shangban' => 'require',
        ], [
            'lat.require' => '坐标不能为空',
            'lng.require' => '坐标不能为空',
            'lat.gt' => '坐标不能为空',
            'lng.gt' => '坐标不能为空',
            'date.require' => '补卡日期不正确',
            'address.require' => '地址不正确',
            'iswai.require' => '补卡类型不能为空',
            'shangban.require' => '上班类型不能为空'
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $lianxu = 1;
        if ($data['iswai'] == 2) {
            $validate = new Validate([
                'images' => 'require',
            ], [
                'images.require' => '图片不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            if ($data['orderid'] == 0 && count($data['orderidarr']) <= 0) {
                // $this->result([], 1, '请选择关联订单');
            }
            if (count($data['orderidarr']) > 0) {
                $orderid = [];
                foreach ($data['orderidarr'] as $order) {
                    if (empty($order['id'])) {
                        $this->result([], 1, '关联任务单数据错误');
                    }
                    $orderid[] = $order['id'];
                }
                sort($orderid);
                $data['orderid'] = implode(',', $orderid);
            }
            $starttime = date('Ymd', time() - 7 * 86400);
            $endtime = date('Ymd', time() -  86400);
            $order_arr = explode(',', $data['orderid']);
            foreach ($order_arr as $arrorder) {
                $chaoseven = (new Sign())->where('yearday', 'between', [$starttime, $endtime])->where("FIND_IN_SET (" . $arrorder . ",orderid)")->where(['user_id' => $this->request->user_id])->count();
                if ($chaoseven >= 7) {
                    $lianxu = 2;
                }
            }
        } else {
            $data['orderid'] = 0;
        }
        $time = strtotime($data['date']);
        $yearday = date('Ymd', $time);
        $years = date('Ym', $time);
        $sign = (new Sign())->where(['user_id' => $this->request->user_id, 'yearday' => $yearday])->find();
        if (!empty($sign)) {
            if ($data['shangban'] == 1 && $sign['monstar'] != 1) {
                $this->result([], 1, '当日上班已打卡');
            }
            if ($data['shangban'] == 2 && $sign['aftstar'] != 1) {
                $this->result([], 1, '当日下班已打卡');
            }
        }
        $signlog = (new Signlog())->where(['user_id' => $this->request->user_id, 'yearday' => $yearday, 'monoraft' => $data['shangban'], 'status' => [1, 3, 4]])->find();
        $postlog = [
            'user_id' => $this->request->user_id,
            'orderid' => $data['orderid'] ?? 0,
            'years' =>  $years,
            'yearday' => $yearday ?? 0,
            'monoraft' => $data['shangban'] ?? 0,
            'type' => $data['iswai'] ?? 0,
            'address' => $data['address'] ?? '',
            'lat' => $data['lat'] ?? 0,
            'lng' => $data['lng'] ?? 0,
            'images' => json_encode($data['images'] ?? [], true) ?? '',
            'texts' => $data['texts'] ?? '',
            'btaddress' => $data['btaddress'] ?? '',
            'btname' => $data['btname'] ?? '',
            'status' => 1,
            'lianxu' => $lianxu,
            'buka' => 2,
        ];
        // if(empty($signlog)){
        //补卡不能超过3次
        $signcount = (new Signlog())->where(['user_id' => $this->request->user_id, 'years' => $years, 'buka' => 2, 'status' => [1, 2]])->count();
        if ($signcount >= 3) {
            $this->result([], 1, '每月补卡次数不能超过3次');
        }
        $post['texts'] = $data['texts'] ?? '';
        $post['btname'] = $data['btname'] ?? '';
        $post['btaddress'] = $data['btaddress'] ?? '';
        // }
        //保存
        Db::startTrans();
        try {
            if (empty($signlog)) {
                (new Signlog())->allowfield(true)->save($postlog);
            } else {
                (new Signlog())->allowfield(true)->save($postlog, ['id' => $signlog['id']]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->result([], 1, $e->getMessage());
        }
        $this->result([], 0, '补卡申请提交成功');
    }

    public function postkaoqin()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'lat' => 'require|gt:0',
            'lng' => 'require|gt:0',
            'address' => 'require',
            'iswai' => 'require',
        ], [
            'lat.require' => '坐标不能为空',
            'lng.require' => '坐标不能为空',
            'lat.gt' => '坐标不能为空',
            'lng.gt' => '坐标不能为空',
            'address.require' => '地址不正确',
            'iswai.require' => '类型不能为空',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        Log::write($data, 'test');
        $status = 2;
        $lianxu = 1;
        if ($data['iswai'] == 2) {
            $validate = new Validate([
                'images' => 'require',
                'texts' => 'require',
            ], [
                'images.require' => '图片不能为空',
                'texts.require' => '备注不正确'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            if ($data['orderid'] == 0 && count($data['orderidarr']) <= 0) {
                //$status = 1;
                //检测7天内是否有选址|开业单
                // if ($this->request->user_id == 108) {
                $cxorders = (new Sign())->order('yearday desc')->where(['user_id' => $this->request->user_id])->value('orderid') ?? 0;
                $cstarttime = date('Ymd', time() - 7 * 86400);
                $order_arrss = explode(',', $cxorders);
                $tanchuang = 1;
                foreach ($order_arrss as $arrorder) {
                    if (!empty($arrorder)) {
                        $chaoseven = (new Sign())->where('yearday', '>', $cstarttime)->where("FIND_IN_SET (" . $arrorder . ",orderid)")->where(['user_id' => $this->request->user_id])->count();
                        if ($chaoseven >= 1) {
                            $tanchuang = 2;
                        }
                    }
                }
                if ($tanchuang == 2) {
                    $this->result([], 1, '存在打卡时间不超过7天的订单，不可无任务单打卡');
                }
                //查询手头选址单
                $xzwhere = [
                    ['duid', '=', $this->request->user_id],
                    ['schedule', '=', 2],
                ];
                //查询手头开业单
                $kywhere = [
                    ['kuid', '=', $this->request->user_id],
                    ['schedule', '=', 5],
                ];
                $haxuanzhi = (new Business())
                    ->whereOr(function ($query) use ($xzwhere) {
                        $query->where($xzwhere);
                    })->whereOr(function ($query) use ($kywhere) {
                        $query->where($kywhere);
                    })->select();
                if (count($haxuanzhi) > 0) {
                    $this->result([], 1, '您有正在进行的任务单，必须关联任务单打卡');
                }
                // }
                //$this->result([], 1, '请选择关联任务单');
            }
            if (count($data['orderidarr']) > 0) {
                $orderid = [];
                foreach ($data['orderidarr'] as $order) {
                    if (empty($order['id'])) {
                        $this->result([], 1, '关联任务单数据错误');
                    }
                    $orderid[] = $order['id'];
                }
                sort($orderid);
                $data['orderid'] = implode(',', $orderid);
            }
            $starttime = date('Ymd', time() - 15 * 86400);
            $endtime = date('Ymd', time() -  7 * 86400);
            $order_arr = explode(',', $data['orderid']);
            foreach ($order_arr as $arrorder) {
                if (!empty($arrorder)) {
                    // $chaoseven = (new Sign())->where('yearday', '<=', $starttime)->where("FIND_IN_SET (" . $arrorder . ",orderid)")->where(['user_id' => $this->request->user_id])->count();
                    $chaoseven = (new Sign())->where('yearday', 'between', [$starttime, $endtime])->where("FIND_IN_SET (" . $arrorder . ",orderid)")->where(['user_id' => $this->request->user_id])->count();
                    if ($chaoseven >= 1) {
                        $status = 1;
                        $lianxu = 2;
                    }
                }
                //查询任务单是否已报销
                $havereimburs = (new Reimburs())->where(['user_id' => $this->request->user_id, 'orderid' => $arrorder, 'status' => 2, 'old' => 1])->find();
                if (!empty($havereimburs)) {
                    $this->result([], 1, '已报销任务单无法继续绑定打卡');
                }
            }
        }
        //上下班标准时间
        $signtime = (new Config())->where('name', 'signtime')->value('value') ?? '';
        $signtime = json_decode($signtime, true) ?? [];
        //判断现在打卡时间是上班卡还是下班卡
        $time = date('H:i');
        $nowtime = date('Y-m-d H:i:s');
        if (date('H:i', strtotime($nowtime) + 3600) < $signtime['mon']) {
            //$this->result([], 1, '打卡时间与上班时间间隔不能超过一个小时');
        }
        //查询当天有没有打卡记录
        $yearday = date('Ymd');
        $sign = (new Sign())->where(['user_id' => $this->request->user_id, 'yearday' => $yearday])->find();
        $post = [];
        $post['orderid'] = $data['orderid'] ?? 0;
        $post['lat'] = $data['lat'] ?? 0;
        $post['lng'] = $data['lng'] ?? 0;
        $postlog = [];
        if (!empty($sign)) {
            $post['aftstar'] = 2;
            $post['after_time'] = $nowtime;
            if ($time < $signtime['aft']) {
                $post['aftstar'] = 3;
            }
            $postlog = [
                'user_id' => $this->request->user_id,
                'orderid' => $data['orderid'] ?? 0,
                'yearday' => $yearday ?? 0,
                'type' => $data['iswai'] ?? 0,
                'monoraft' => 2,
                'years' =>  date('Ym'),
                'address' => $data['address'] ?? '',
                'status' => $status,
                'lianxu' => $lianxu,
                'lat' => $data['lat'] ?? 0,
                'lng' => $data['lng'] ?? 0,
                'images' => json_encode($data['images'] ?? [], true) ?? '',
                'texts' => $data['texts'] ?? '',
                'btaddress' => $data['btaddress'] ?? '',
                'btname' => $data['btname'] ?? '',
            ];
        } else {
            $monoraft = 0;
            //判断是上班卡还是下班卡
            if (time() < (strtotime($signtime['aft']) - 3 * 3600)) {
                $monoraft = 1;
            } else {
                $monoraft = 2;
            }
            $post['user_id'] = $this->request->user_id;
            $post['years'] = date('Ym');
            $post['yearday'] = date('Ymd');
            //上班卡
            if ($monoraft == 1) {
                $post['monstar'] = 2;
                $post['month_time'] = $nowtime;
                //判定迟到
                if ($time > $signtime['mon']) {
                    $post['monstar'] = 3;
                }
            } else {
                $post['aftstar'] = 2;
                $post['after_time'] = $nowtime;
                //判定早退
                if ($time < $signtime['aft']) {
                    $post['aftstar'] = 3;
                }
            }
            $postlog = [
                'user_id' => $this->request->user_id,
                'orderid' => $data['orderid'] ?? 0,
                'years' =>  date('Ym'),
                'yearday' => $yearday ?? 0,
                'type' => $data['iswai'] ?? 0,
                'monoraft' => $monoraft,
                'address' => $data['address'] ?? '',
                'lat' => $data['lat'] ?? 0,
                'lng' => $data['lng'] ?? 0,
                'status' => $status,
                'lianxu' => $lianxu,
                'images' => json_encode($data['images'] ?? [], true) ?? '',
                'texts' => $data['texts'] ?? '',
                'btaddress' => $data['btaddress'] ?? '',
                'btname' => $data['btname'] ?? '',
            ];
        }
        $addresstext = '';
        if ($post['lat'] > 0 && $post['lng'] > 0) {
            $url = 'https://restapi.amap.com/v3/geocode/regeo';
            $city = '';
            try {
                $res = api_curl($url, ['location' => $post['lng'] . ',' . $post['lat'], 'key' => 'c400abfe779387dc8ded64d7db8dbbac', 'extensions' => 'base']);
                if (!empty($res['regeocode']['addressComponent'])) {
                    if (empty($res['regeocode']['addressComponent']['city']) || is_array($res['regeocode']['addressComponent']['city'])) {
                        $city = $res['regeocode']['addressComponent']['province'] ?? '';
                    } else {
                        $city = $res['regeocode']['addressComponent']['city'] ?? '';
                    }
                    if (empty($res['regeocode']['addressComponent']['district']) || is_array($res['regeocode']['addressComponent']['district'])) {
                        $street  = '';
                    } else {
                        $street = $res['regeocode']['addressComponent']['district'] ?? '';
                    }
                    if (!empty($postlog['address']) && $postlog['address'] == '未获取到位置信息,请检查相关权限是否开启') {
                        $postlog['address']  = $res['regeocode']['formatted_address']  ?? "";
                    }
                    $addresstext = $city . $street;
                }
            } catch (\Exception $e) {
            }
            if ($city == '长沙市' && $lianxu == 2) {
                $this->result([], 1, '长沙市内无法打卡超期任务单');
            }
        }
        if (!empty($addresstext)) {
            $post['addresstext'] = $addresstext;
        }
        $signlog = (new Signlog())->where([
            'user_id' => $this->request->user_id,
            'yearday' => $yearday,
            'monoraft' => $postlog['monoraft'],
            'status' => [1, 3, 4]
        ])->find();
        $text = '打卡成功';
        if ($lianxu == 2) {
            $text = '本单已经超过7天,已提交打卡申请待审核!';
            // $this->result([], 1, '本单已经超过7天，超过工作期限，不允许打卡');
        } elseif ($status == 1) {
            $text = '打卡申请提交成功,待审核!';
        }
        $post['texts'] = $data['texts'] ?? '';
        $post['btname'] = $data['btname'] ?? '';
        $post['btaddress'] = $data['btaddress'] ?? '';
        Db::startTrans();
        try {
            if ($status == 2) {
                if (empty($sign)) {
                    (new Sign())->allowfield(true)->save($post);
                } else {
                    (new Sign())->allowfield(true)->save($post, ['id' => $sign['id']]);
                }
            }
            if (empty($signlog)) {
                (new Signlog())->allowfield(true)->save($postlog);
            } else {
                (new Signlog())->allowfield(true)->save($postlog, ['id' => $signlog['id']]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->result([], 1, $e->getMessage());
        }
        $this->result([], 0, $text);
    }

    public function getsigndata()
    {
        $data = $this->request->get();
        $ymd = $this->request->get('ymd', date('Ymd'));
        $ym = date('Ym');
        if (!empty($ymd)) {
            $ym = date('Ym', strtotime($ymd));
        } else {
            $ymd = date('Ymd');
            $ym = date('Ym', strtotime($ymd));
        }
        $page = $data['page'] ?? 1;
        $userid = $this->request->get('userid/d', $this->request->user_id);
        $queka = (new Sign())->where(['years' => $ym, 'monstar' => 1, 'user_id' => $userid])->count() + (new Sign())->where(['years' => $ym, 'user_id' => $userid, 'aftstar' => 1])->count();
        //旷工
        $kuanggong = 0;
        //旷工计算
        if ($ym == date('Ym')) {
            $days = date('d') - 1;
            $kuanggong = $days - (new Sign())->where(['years' => $ym, 'user_id' => $userid])->where('yearday', '<>', date('Ymd'))->count();
        } elseif ($ym < date('Ym')) {
            $year = substr($ym, 0, 4);
            $month = substr($ym, 4, 2);
            $date = $year . '-' . $month . '-01'; // 假设是月初的时间戳
            $days = date('t', strtotime($date));
            $kuanggong = $days - (new Sign())->where(['years' => $ym, 'user_id' => $userid])->count();
        }
        if ($ymd < date('Ymd')) {
            $nowdaysign = (new Sign())->where(['yearday' => $ymd, 'user_id' => $userid])->find();
            $sign = [
                'monstar' => (int)($nowdaysign['monstar'] ?? 1), //上班卡
                'aftstar' => (int)($nowdaysign['aftstar'] ?? 1), //下班卡
            ];
        } else {
            $sign = [
                'monstar' => 2, //上班卡
                'aftstar' => 2, //下班卡
            ];
        }
        $result2 = [
            'sign' => $sign,
            'name' => (new Users())->where(['id' => $userid])->value('account'),
            'chidao' => (new Sign())->where(['years' => $ym, 'monstar' => 3, 'user_id' => $userid])->count(), //迟到次数
            'zaotui' => (new Sign())->where(['years' => $ym, 'aftstar' => 3, 'user_id' => $userid])->count(), //早退次数
            'daka' => (new Sign())->where(['years' => $ym, 'user_id' => $userid])->count(), //打卡次数
            'queka' => $queka, //缺卡
            'kuanggong' => $kuanggong
        ];
        $result = (new Signlog())->where(['user_id' => $userid])->page($page)->order(['created' => 'desc']);
        if (!empty($ymd)) {
            $result = $result->where('yearday', $ymd);
        }
        $result = $result->limit(15)->select();
        foreach ($result as $row) {
            $row['images'] = json_decode($row['images'], true);
            $row['typetext'] = '外勤';
            $row['monorafttext'] = '上班打卡';
            if ($row['type'] == 1) {
                $row['typetext'] = '内勤';
            }
            if ($row['monoraft'] == 2) {
                $row['monorafttext'] = '下班打卡';
            }
            if (!empty($row['orderid'])) {
                $orderid = explode(',', $row['orderid']) ?? [0];
                $kehu = (new Business())->where(['id' => $orderid])->select();
                $row['kehuname'] = '';
                $row['kehuphone'] = '';
                $row['kehuid'] = '';
                $row['kehuaddress'] = '';
                foreach ($kehu as $ke) {
                    $row['kehuid'] =  $row['kehuid'] . '[' . $ke['id'] . ']';
                    $row['kehuname'] =  $row['kehuname'] . '[' . $ke['name'] . ']';
                    $row['kehuphone'] =  $row['kehuphone'] . '[' . $ke['phone'] . ']';
                    $row['kehuaddress'] =  $row['kehuaddress'] . '[' . ($ke['address'] ?? '') . ($ke['getaddress'] ?? '') . ']';
                }
            }
        }
        $this->result(['data' => $result, 'data2' => $result2], 0, '获取成功');
    }



    public function usersigndetailall()
    {
        $data = $this->request->get();
        $list = (new Signlog())->order(['created' => 'desc', 'yearday' => 'desc', 'id' => 'desc']);
        $page = $data['page'] ?? 1;
        $page = (int)$page;
        $list = $list->where(['status' => [1, 2, 3]]);
        if (!empty($data['user_id'])) {
            $list = $list->where('user_id', $data['user_id']);
        }
        if (!empty($data['monoraft'])) {
            $list = $list->where('monoraft', $data['monoraft']);
        }
        if (!empty($data['type'])) {
            $list = $list->where('type', $data['type']);
        }
        if (!empty($data['buka'])) {
            $list = $list->where('buka', $data['buka']);
        }
        if (!empty($data['status'])) {
            $list = $list->where('status', $data['status']);
        }
        if (!empty($data['dates'])) {
            $yearday = date('Ymd', strtotime($data['dates']));
            $list = $list->where('yearday', $yearday);
        } else {
            // $yearday = date('Ymd');
            // $list = $list->where('yearday', $yearday);
        }
        $list = $list->limit(10)->page($page)->select();
        foreach ($list as $result) {
            $result['images'] = json_decode($result['images'], true);
            $result['user_name'] = (new Users())->where(['id' => $result['user_id']])->value('account') ?? '';
            if ($result['lianxu'] == 2) {
                $result['user_name'] = $result['user_name'] . '(打卡超7天)';
            }
        }
        $this->result($list, 0, '获取成功');
    }

    public function sucai()
    {

        $data = $this->request->get();
        if ($this->request->user['type'] != 4 && $this->request->user['type'] != 5 && $this->request->user['type'] != 7) {
            $this->result(['list' => [], 'statuslist' => []], 0, '操作成功');
        }
        $page = $data['page'] ?? 1;
        $limit =  $data['limit'] ?? 5;
        $status =  $data['status'] ?? 'video3';
        $page = (int)$page;
        $limit = (int)$limit;
        $sort = ['jcupdated' => 'desc'];
        $times = '';
        $uid = '';
        if (in_array($status, ['images', 'images4', 'images10', 'video1', 'video1', 'video4'])) {
            $sort = ['jcupdated' => 'desc', 'xtimes' => 'desc'];
            $times = 'jcupdated';
            $uid = 'duid';
        } elseif (in_array($status, ['images', 'image6', 'images7', 'images9', 'images11', 'images12', 'video3'])) {
            $sort = ['htupdated' => 'desc', 'xtimes' => 'desc'];
            $times = 'htupdated';
            $uid = 'duid';
        } else {
            $sort = ['kyupdated' => 'desc', 'times' => 'desc'];
            $times = 'kyupdated';
            $uid = 'kuid';
        }
        $results = (new Business())->whereNotNull($status)->where($status, '<>', '[]');
        $groups = [];
        if (!empty($this->request->user['groups']) && $this->request->user['type'] == 7) {
            $groups = explode(',', $this->request->user['groups']) ?? [];
            $results = $results->where(['type' => $groups]);
        }
        $results = $results->order($sort)->limit($limit)->page($page)->order('id desc')->select();
        $list = [];
        $statuslist = [[
            'id' =>  'images3',
            'name' => '选址周边照片'
        ], [
            'id' =>  'images4',
            'name' => '现场选址照片'
        ], [
            'id' =>  'images10',
            'name' => '店内照片'
        ], [
            'id' =>  'images12',
            'name' =>  '选址成功手拉旗照'
        ], [
            'id' =>  'video1',
            'name' =>  '选址现场视频'
        ], [
            'id' =>  'video4',
            'name' =>  '选址工作途中视频'
        ], [
            'id' =>  'video3',
            'name' =>  '签合同视频'
        ], [
            'id' =>  'video',
            'name' =>  '开业现场视频'
        ], [
            'id' =>  'video5',
            'name' =>  '开业人气视频'
        ], [
            'id' =>  'video6',
            'name' =>  '开业工作途中视频'
        ]];
        foreach ($statuslist as $kw => $rwlist) {
            $rdsgettims = Redis::get($rwlist['id'] . $this->request->user_id);
            if (!$rdsgettims) {
                $rdsgettims = time() - 7 * 86400;
            }
            $rwhave = (new Business())->whereNotNull($rwlist['id'])->where($rwlist['id'], '<>', '[]');
            if (!empty($this->request->user['groups']) && $this->request->user['type'] == 7) {
                $groups = explode(',', $this->request->user['groups']) ?? [];
                $rwhave  = $rwhave->where(['type' => $groups]);
            }
            if (in_array($rwlist['id'], ['images', 'images4', 'images10', 'video1', 'video1', 'video4'])) {
                $times = 'jcupdated';
            } elseif (in_array($rwlist['id'], ['images', 'image6', 'images7', 'images9', 'images11', 'images12', 'video3'])) {
                $times = 'htupdated';
            } else {
                $times = 'kyupdated';
            }
            $wheretime = date('Y-m-d H:i:s', (int)$rdsgettims);
            $rwhave  = $rwhave->whereTime($times, '>=', $wheretime)->count();
            if ($rwhave > 0) {
                $statuslist[$kw]['badge'] = ['value' => $rwhave];
            }
        }
        Redis::set($status . $this->request->user_id, time());
        $type = 1;
        if (in_array($status, ['video', 'video1', 'video2', 'video3', 'video4', 'video5', 'video6', 'video7', 'video8', 'video9', 'video10'])) {
            $type = 2;
        }
        // 创建FFMpeg对象
        $ffmpeg = FFMpeg::create([
            'ffmpeg.binaries' => '/www/server/ffmpeg/ffmpeg-6.1/ffmpeg',    //FFmpeg的运行目录  服务器上的安装位置
            'ffprobe.binaries' => '/www/server/ffmpeg/ffmpeg-6.1/ffprobe'    //ffprobe的运行目录 服务器上的安装位置
        ]);
        foreach ($results as $row) {
            //选址督导信息
            $dudaoinfo = (new Users())->where('id', $row[$uid])->find();
            $dudao = $dudaoinfo['account'] ?? ''; //选址督导
            $dudao = $dudao . '(' . ($dudaoinfo['mobile'] ?? '') . ')'; //选址督导电话
            $dudaomobile = $dudaoinfo['mobile'] ?? ''; //选址督导电话
            $kehu = $row['name'];
            $address = $row['getaddress'] . '(' . $row['address'] . ')';
            $sucai = json_decode($row[$status], true) ?? [];
            foreach ($sucai as $k => $scs) {
                $sucai[$k]['sucaiid'] = $row['id'] . '1000' . ($k + 1);
                $sucai[$k]['duration'] = 0;
                if ($type == 2) {
                    $scrdsname = 'sucai_' . $status . '_' . md5($scs['url']);
                    $scduration = Redis::get($scrdsname);
                    if (!$scduration) {
                        try {
                            //打开视频文件
                            $video = $ffmpeg->open($scs['url']);
                            // 获取视频时长
                            $duration = $video->getStreams()->first()->get('duration'); // 单位：秒
                            $sucai[$k]['duration'] = floor($duration * 100) / 100;
                            Redis::set($scrdsname, $sucai[$k]['duration']);
                        } catch (\Exception $e) {
                        }
                    } else {
                        $sucai[$k]['duration'] = (float)$scduration;
                    }
                } else {
                    $sucai[$k]['url'] = $scs['url'] . '?x-oss-process=image/resize,l_1200,q_90';
                }
            }
            if (count($sucai) > 0) {
                $list[] = ['kehu' => $kehu, 'dudaomobile' => $dudaomobile, 'dudao' => $dudao, 'address' => $address, 'type' => $type, 'url' => $sucai, 'times' => ($row[$times] ? $row[$times] : $row['created'])];
                //1表示相片2表示视频
            }
        }
        $this->result(['list' => $list, 'statuslist' => $statuslist], 0, '操作成功');
    }

    public function dingzhuanxuan()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
                'status' => 'require',
            ], [
                'status.require' => '操作类型不能为空',
                'id.require' => 'ID不能为空'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            if ($this->request->user['type'] != 4) {
                $this->result([], 1, '无权操作此项');
            }
            $dingorxuan = (new Dingorxuan())->where(['id' => $data['id']])->find();
            if (empty($dingorxuan)) {
                $this->result([], 1, '提交单不存在');
            }
            if ($dingorxuan['status'] != 1) {
                $this->result([], 1, '提交单已审核');
            }
            $business = (new Business())->where(['id' => $dingorxuan['orderid']])->find();
            switch ($data['status']) {
                case '2':
                    if (empty($business)) {
                        $this->result([], 1, '关联单不存在');
                    }
                    if ($business['ordertype'] != 2 && $business['ordertype'] != 12) {
                        $this->result([], 1, '关联订单非定店类型');
                    }
                    if ($business['ordertype'] == 1) {
                        $this->result([], 1, '关联订单已经是首选址类型');
                    }
                    Db::startTrans();
                    try {
                        (new Messages())->allowfield(true)->save([
                            'type' => 1,
                            'orderid' => $dingorxuan['orderid'],
                            'user_id' =>  $dingorxuan['user_id'],
                            'ouser_id' => 0,
                            'status' => 1,
                            'endstatus' => 0,
                            'text' => '定店转选址审核通过!',
                            'yue' => 2
                        ]);
                        (new Business())->where(['id' => $dingorxuan['orderid']])->update(['ordertype' => 1]);
                        (new Dingorxuan())->where(['id' => $data['id']])->update(['status' => $data['status']]);
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        $this->result([], 1, $e->getMessage());
                    }
                    $this->result([], 0, '操作成功');
                    break;
                case '9':
                    if (empty($business)) {
                        return json(['status' => 1, 'data' => [], 'msg' => '关联订单不存在']);
                    }
                    if ($business['ordertype'] != 2 && $business['ordertype'] != 12) {
                        return json(['status' => 1, 'data' => [], 'msg' => '关联订单非定店类型']);
                    }
                    if ($business['ordertype'] == 11) {
                        return json(['status' => 1, 'data' => [], 'msg' => '关联订单已经是二次选址类型']);
                    }
                    Db::startTrans();
                    try {
                        (new Messages())->allowfield(true)->save([
                            'type' => 1,
                            'orderid' => $dingorxuan['orderid'],
                            'user_id' =>  $dingorxuan['user_id'],
                            'ouser_id' => 0,
                            'status' => 1,
                            'endstatus' => 0,
                            'text' => '定店转选址审核通过!',
                            'yue' => 2
                        ]);
                        (new Business())->where(['id' => $dingorxuan['orderid']])->update(['ordertype' => 11]);
                        (new Dingorxuan())->where(['id' => $data['id']])->update(['status' => 2]);
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        $this->result([], 1, $e->getMessage());
                    }
                    $this->result([], 0, '操作成功');
                    break;
                case '3':
                    Db::startTrans();
                    try {
                        (new Messages())->allowfield(true)->save([
                            'type' => 1,
                            'orderid' => $dingorxuan['orderid'],
                            'user_id' =>  $dingorxuan['user_id'],
                            'ouser_id' => 0,
                            'status' => 1,
                            'endstatus' => 0,
                            'text' => '定转选驳回,' . $data['value'] ?? '',
                            'yue' => 2
                        ]);
                        (new Dingorxuan())->where(['id' => $data['id']])->update(['status' => $data['status'], 'text' => $data['value'] ?? '']);
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        $this->result([], 1, $e->getMessage());
                    }
                    $this->result([], 0, '操作成功');
                    break;
                default:
                    $this->result([], 1, '状态成功');
                    break;
            }
        } else {
            $data = $this->request->get();
            $list = (new Dingorxuan())->alias('d')->field('d.*')->leftjoin('business b', 'd.orderid = b.id')->order('id desc');
            $page = $data['page'] ?? 1;
            $page = (int)$page;
            if (!empty($data['user_id'])) {
                $list = $list->where('d.user_id', $data['user_id']);
            }
            if (!empty($data['status'])) {
                $list = $list->where('d.status', $data['status']);
            }
            if (!empty($data['title'])) {
                $list = $list->where('b.areas|b.title|b.address|b.phone|b.mobile|b.phone2|b.name2|b.getaddress|b.name|b.province|b.city|b.area', 'like', '%' . $data['title'] . '%');
            }
            $list = $list->limit(5)->page($page)->select();
            foreach ($list as $result) {
                $result['dudao'] = (new Users())->where('id', $result['user_id'])->value('account') ?? '';
                $result['datas'] = json_decode($result['datas'], true);
            }
            $this->result($list, 0, '获取成功');
        }
    }

    public function marklist()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
                'status' => 'require',
            ], [
                'status.require' => '操作类型不能为空',
                'id.require' => 'ID不能为空'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $reimburs = (new Marks())->where(['id' => $data['id'], 'status' => 1])->find();
            if (empty($reimburs)) {
                return json(['status' => 1, 'data' => [], 'msg' => '信息不存在或处于不可审核状态']);
            }
            $adminid = 1;
            switch ($data['status']) {
                case '2':
                    if ($this->request->user['type'] != 4) {
                        $this->result([], 1, '无权操作此项');
                    }
                    $data['value'] = $data['value'] ?? '';
                    Db::startTrans();
                    try {
                        (new Marks())->where(['id' => $data['id'], 'status' => 1])->update(['status' => $data['status'], 'text' => $data['value'], 'type' => 2]);
                        (new Messages())->allowfield(true)->save([
                            'type' => 4,
                            'orderid' => $data['id'],
                            'user_id' =>  $reimburs['user_id'],
                            'ouser_id' => 0,
                            'status' => 1,
                            'endstatus' => 0,
                            'text' => $reimburs['title'] . '拓展库审核通过!',
                            'yue' => 2
                        ]);
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        $this->result([], 1, $e->getMessage());
                    }
                    $this->result([], 0, '操作成功');
                    break;
                case '3':
                    if ($this->request->user['type'] != 4) {
                        $this->result([], 1, '无权操作此项');
                    }
                    if (empty($data['value'])) {
                        $this->result([], 1, '请填写驳回理由');
                    }
                    Db::startTrans();
                    try {
                        (new Marks())->where(['id' => $data['id'], 'status' => 1])->update(['status' => $data['status'], 'text' => $data['value']]);
                        (new Messages())->allowfield(true)->save([
                            'type' => 4,
                            'orderid' => $data['id'],
                            'user_id' =>  $reimburs['user_id'],
                            'ouser_id' => 0,
                            'status' => 2,
                            'endstatus' => 0,
                            'text' => $reimburs['title'] . '拓展库信息被驳回!',
                            'yue' => 2
                        ]);
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        $this->result([], 1, $e->getMessage());
                    }
                    $this->result([], 0, '操作成功');
                    break;
                default:
                    $this->result([], 1, '状态错误');
                    break;
            }
        } else {
            $model = new Marks();
            $data = $this->request->get();
            $page = $data['page'] ?? 1;
            $page = (int)$page;
            $results = $model->alias('m')->field('m.*,u.account as dudaoname')->order('m.id desc')->leftjoin('user u', 'm.user_id = u.id');
            if (!empty($data['search'])) {
                $results = $results->where('m.title|m.reAddress|m.address|m.texts', 'like', '%' . $data['search'] . '%');
            }
            if (!empty($data['type'])) {
                $results = $results->where('m.type', $data['type']);
            }
            if (!empty($data['status'])) {
                $results = $results->where('m.status', $data['status']);
            }
            if (!empty($data['user_id'])) {
                $results = $results->where('m.user_id', $data['user_id']);
            }
            if ($this->request->user['type'] != 4) {
                $results = $results->where('m.user_id', $this->request->user_id);
            }
            $results = $results->limit(5)->page($page)->select();
            $shenhe = 1;
            if ($this->request->user['type'] == 4) {
                $shenhe = 2; //审核权限 
            }
            foreach ($results as $result) {
                $result['shenhe'] = $shenhe;
                $result['fileList1'] = json_decode($result['fileList1'], true) ?? [];
                $result['fileList2'] = json_decode($result['fileList2'], true) ?? [];
                $result['fileList10'] = json_decode($result['fileList10'], true) ?? [];
            }
            $this->result($results, 0, '获取成功');
        }
    }

    public function bxlist()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
                'status' => 'require',
            ], [
                'status.require' => '操作类型不能为空',
                'id.require' => 'ID不能为空'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $reimburs = (new Reimburs())->where(['id' => $data['id'], 'status' => [1, 2]])->find();
            if (empty($reimburs)) {
                return json(['status' => 1, 'data' => [], 'msg' => '订单不存在或处于不可审核状态']);
            }
            $adminid = 1;
            switch ($data['status']) {
                case '2':
                    if ($this->request->user['type'] != 4) {
                        $this->result([], 1, '无权操作此项');
                    }
                    $data['value'] = $data['value'] ?? '';
                    $groups = $reimburs['groups'];
                    if (!empty($data['groups'])) {
                        $groups = $data['groups'];
                    }
                    Db::startTrans();
                    try {
                        (new Reimburs())->where(['id' => $data['id'], 'status' => 1])->update(['status' => $data['status'], 'text' => $data['value'], 'adminid' => $adminid, 'groups' => $groups]);
                        (new Messages())->allowfield(true)->save([
                            'type' => 2,
                            'orderid' => $data['id'],
                            'user_id' =>  $reimburs['user_id'],
                            'ouser_id' => 0,
                            'status' => 1,
                            'endstatus' => 0,
                            'text' => '报销申请审核通过，请等待打款!',
                            'yue' => 2
                        ]);
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        $this->result([], 1, $e->getMessage());
                    }
                    $this->result([], 0, '操作成功');
                    break;
                case '3':
                    if ($this->request->user['type'] != 4) {
                        $this->result([], 1, '无权操作此项');
                    }
                    if (empty($data['value'])) {
                        $this->result([], 1, '请填写驳回理由');
                    }
                    Db::startTrans();
                    try {
                        (new Reimburs())->where(['id' => $data['id'], 'status' => 1])->update(['status' => $data['status'], 'text' => $data['value'], 'adminid' => $adminid]);
                        (new Messages())->allowfield(true)->save([
                            'type' => 2,
                            'orderid' => $data['id'],
                            'user_id' =>  $reimburs['user_id'],
                            'ouser_id' => 0,
                            'status' => 2,
                            'endstatus' => 0,
                            'text' => '报销申请被驳回!',
                            'yue' => 2
                        ]);
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        $this->result([], 1, $e->getMessage());
                    }
                    $this->result([], 0, '操作成功');
                    break;
                case '8':
                    if ($this->request->user['type'] != 4 || $this->request->user['type'] != 5) {
                        $this->result([], 1, '无权操作此项');
                    }
                    if ($reimburs['status'] != 2) {
                        $this->result([], 1, '该订单未审核通过无法撤销重审');
                    }
                    Db::startTrans();
                    try {
                        (new Reimburs())->where(['id' => $data['id'], 'status' => 2])->update(['dk' => 1, 'status' => 1]);
                        (new Messages())->allowfield(true)->save([
                            'type' => 2,
                            'orderid' => $data['id'],
                            'user_id' =>  $reimburs['user_id'],
                            'ouser_id' => 0,
                            'status' => 3,
                            'endstatus' => 0,
                            'text' => '报销申请被撤回重新审核!',
                            'yue' => 2
                        ]);
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        $this->result([], 1, $e->getMessage());
                    }
                    $this->result([], 0, '操作成功');
                    break;
                case '9':
                    if ($this->request->user['type'] != 5) {
                        $this->result([], 1, '无权操作此项');
                    }
                    if ($reimburs['status'] != 2) {
                        $this->result([], 1, '该订单未审核通过无法确认打款');
                    }
                    Db::startTrans();
                    try {
                        (new Reimburs())->where(['id' => $data['id'], 'status' => 2])->update(['dk' => 2]);
                        (new Messages())->allowfield(true)->save([
                            'type' => 2,
                            'orderid' => $data['id'],
                            'user_id' =>  $reimburs['user_id'],
                            'ouser_id' => 0,
                            'status' => 4,
                            'endstatus' => 0,
                            'text' => '报销被标记已打款!',
                            'yue' => 2
                        ]);
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        $this->result([], 1, $e->getMessage());
                    }
                    $this->result([], 0, '操作成功');
                    break;
                default:
                    $this->result([], 1, '状态错误');
                    break;
            }
        } else {
            $model = new Reimburs();
            $data = $this->request->get();
            $page = $data['page'] ?? 1;
            $page = (int)$page;
            $results = $model->alias('rs')->field('rs.*')->leftjoin('business b', 'rs.orderid = b.id')->order('rs.id desc');
            if (!empty($data['search'])) {
                $results = $results->where('rs.name|rs.address|rs.text|b.areas|b.title|b.phone|b.address|b.phone|b.mobile|b.phone2|b.name2|b.getaddress|b.name|b.province|b.city|b.area', 'like', '%' . $data['search'] . '%');
            }
            if (!empty($data['type'])) {
                $results = $results->where('rs.type', $data['type']);
            }
            if (!empty($data['xmtype'])) {
                $results = $results->where('rs.groups|b.type', $data['xmtype']);
            }
            if (!empty($data['status'])) {
                $results = $results->where('rs.status', $data['status']);
            } elseif ($this->request->user['type'] == 5) {
                $results = $results->where('rs.status', 2);
            }
            if (!empty($data['ordertype'])) {
                $results = $results->where('rs.jobtype|b.ordertype', $data['ordertype']);
            }
            if (!empty($data['dk'])) {
                $results = $results->where('rs.dk', $data['dk'])->where('rs.status', 2);
            }
            if (!empty($data['reimburs_type'])) {
                $colun = (new ReimbursLog())->where('type', $data['reimburs_type'])->column('id');
                $results = $results->where(['rs.id' => $colun]);
            }
            if (!empty($data['user_id'])) {
                $results = $results->where('rs.user_id', $data['user_id']);
            }
            $results = $results->limit(5)->page($page)->select();
            $shenhe = 1; //审核权限 
            $dk = 1; //打款权限
            if ($this->request->user['type'] == 4) {
                $shenhe = 2; //审核权限 
            }
            if ($this->request->user['type'] == 5) {
                $dk = 2; //审核权限 
            }
            foreach ($results as $result) {
                $result['shenhe'] = $shenhe;
                $result['isdk'] = $dk;
                $result['typename'] = '';
                if ($result['type'] == 1) {
                    $result['typename'] = '选址';
                }
                if ($result['type'] == 2) {
                    $result['typename'] = '开业';
                }
                if ($result['type'] == 99) {
                    $result['typename'] = '日常报销';
                }
                if ($result['type'] == 100) {
                    $result['typename'] = '费用预支';
                }
                $business = (new Business())->where('id', $result['orderid'])->find() ?? '';
                //任务单状态返回
                $schedule = (new Business())->where('id', $result['orderid'])->value('schedule') ?? 0;
                $adminuser = (new Admin())->where('id', $result['adminid'])->value('nickname') ?? '';
                $result['schedule_text'] = config()["config"]['schedule_nav'][$schedule] ?? '';
                $result['schedule_text2'] = config()["config"]['schedule_text'][$schedule] ?? '';
                $result['user_name'] = (new Users())->where('id', $result['user_id'])->value('account') ?? '用户已删除';
                $result['status_text'] = config()["config"]['reimburs_status'][$result['status']] ?? '';
                $result['status_text'] = config()["config"]['reimburs_status'][$result['status']] ?? '';
                if (empty($business)) {
                    $result['groupname'] = config()["config"]['typeo'][$result['groups']] ?? '';
                } else {
                    $result['groupname'] = config()["config"]['typeo'][$business['type']] ?? '';
                }
                $result['jobtypename'] = config()["config"]['ordertype'][$result['jobtype']] ?? '';
                $result['hktype_text'] = config()["config"]['hktype_text'][$result['hktype']] ?? '未填写';
                $result['name'] = $business['name'] ?? '';
                $result['phone'] = $business['phone'] ?? '';
                $logs = (new ReimbursLog())->where('reimbursid', $result['id'])->select();
                foreach ($logs as $log) {
                    $log['pinzheng'] = json_decode($log['pinzheng'] ?? '', true) ?? [];
                    $log['fujian'] = json_decode($log['fujian'] ?? '', true) ?? [];
                    $log['typename'] = config()["config"]['reimburs_type'][$log['type']] ?? '';
                    $log['mingxi'] = json_decode($log['mingxi'] ?? '', true) ?? [];
                    if ($log['isnew'] == 2) {
                        if (!empty($log['cfdates'])) {
                            $log['remark'] = $log['cfdates'] . ' ~ ' . $log['dddates'] . '  ' . $log['cfaddress'] . '至' . $log['ddaddress'] . $log['kehuname'] . $log['gztype_name'];
                        }
                        foreach ($log['mingxi'] as $mingxi) {
                            $log['remark'] = $log['remark'] . '
    ' . ($mingxi['title'] ?? '') . '(' . ($mingxi['total'] ?? 0) . '元)';
                        }
                    }
                }
                $result['log'] = $logs;
                $result['peoples'] = $adminuser;
                //查询督导上月合同邮寄单
                $result['htshenghe'] = 0;
                $qishu = date('Ym', strtotime('-1 month'));
                $uporder = (new Uploadtk())->where(['user_id' => $result['user_id'], 'qishu' => $qishu])->find();
                if (!empty($uporder)) {
                    $result['htshenghe'] = $uporder['status'];
                }
                $result['cishu'] = (new Users())->where('id', $result['user_id'])->value('hjtz') ?? 0;
            }
            $this->result($results, 0, '获取成功');
        }
    }
}
